Alternative of strcpy in c++

Aerus picture Aerus · Jan 20, 2011 · Viewed 30k times · Source

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 ?

Answer

Zac Howland picture Zac Howland · Jan 20, 2011

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