I wonder if it's possible to shallow copy char*
to std::string
.
If you aim at constructing a std::string object with a char* without copying the data: no, this is impossible. std::string owns its resources, it can't refer to another char* . This is also why the appropriate constructor takes a const char* , not a char* : it doesn't modify the data, but copies it.
Use std::string when you need to store a value. Use const char * when you want maximum flexibility, as almost everything can be easily converted to or from one.
If you aim at constructing a std::string
object with a char*
without copying the data: no, this is impossible. std::string
owns its resources, it can't refer to another char*
. This is also why the appropriate constructor takes a const char*
, not a char*
: it doesn't modify the data, but copies it.
In C++17, you have std::string_view
which is exactly meant for referring to a string (literal) that it doesn't own. Note that this view isn't intended to modify the data, its hence constructed with const char*
again, not char*
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With