Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alternative of strcpy in c++

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 ?

like image 953
Aerus Avatar asked Jan 20 '11 19:01

Aerus


1 Answers

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
like image 167
Zac Howland Avatar answered Oct 10 '22 19:10

Zac Howland