In C i used strcpy
to make a deep copy of a string, but is it still 'fine' to use strcpy
in C++ or are there better alternatives which i should use instead ?
I put this in the comment above, but just to make the code readable:
std::string a = "Hello.";
std::string b;
b = a.c_str(); // makes an actual copy of the string
b = a; // makes a copy of the pointer and increments the reference count
So if you actually want to mimic the behavior of strcpy
, you'll need to copy it using c_str()
;
UPDATE
It should be noted that the C++11 standard explicitly forbids the common copy-on-write pattern that was used in many implementations of std::string
previously. Thus, reference counting strings is no longer allowed and the following will create a copy:
std::string a = "Hello.";
std::string b;
b = a; // C++11 forces this to be a copy as well
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