Home > Mobile >  Is changing the std::string value through it's address is valid?
Is changing the std::string value through it's address is valid?

Time:11-27

I was wondering if we can modify std::string value through a pointer to it. Please consider the following example.

#include <iostream>

void func(std::string *ptr) {
    *ptr = "modified_string_in_func";
}
int main()
{
    std::string str = "Original string";
    func(&str);
    std::cout << "str = " << str << std::endl;
    return 0;
}

I tried GCC, Clang & Visual C . All are modifying the string valirable str without any warning or error but I'm not very sure if it's legal to do so.

Please clarify.

CodePudding user response:

That is legal.

You are assigning a new value to the string but are using a pointer to refer to the original string; this is no more illegal then not using a pointer to refer to the original string i.e.

std::string foo = "foo";
foo = "bar";

// is pretty much the same thing as

std::string* foo_ptr = &foo;
*foo_ptr = "bar";

// which is what you are doing.
  • Related