tistCoder tistCoder - 1 year ago 62
C++ Question

Is it possible to initialize a const char* with a rvalue like string.c_str()?

const char* s = std::string("text").c_str();
std::cout << s << std::endl; //This will print nothing because the data
//isn't available any longer

returns a pointer to it's stored data.
In fact that
is just available for the time i use it (e.g. when I use it initialize an other instance) so in the end the destructor is called which deletes the data which makes s pointing to nothing.

Now my question is if there is a way to move the data somewhere where it's not deleted by the destructor so
const char*
can point to it. Or is it just possible if they would use something like a shared-smart-pointer which knows if something else is pointing to the
's data so it is not deleted yet.

Copying the data somewhere and pointing to that isn't what I'm looking for.

pat pat
Answer Source

A string cannot be made to use reference counted pointers internally. If you wish to use a pointer to its data, you must make sure the string survives. The only alternative is copying / moving the data out into another string object.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download