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 ?
问题:
回答1:
In C++ the easiest way is usually to use the std::string class instead of char*.
#include <string>
...
std::string a = "Hello.";
std::string b;
b = a;
The line "b = a;" does the same thing you would usually do with strcpy.
回答2:
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
回答3:
If you're using c++ strings, just use the copy constructor:
std::string string_copy(original_string);
Of assignment operator
string_copy = original_string
If you must use c-style strings (i.e. null-terminated char arrays), then yeah, just use strcpy, or as a safer alternative, strncpy.
回答4:
You are suggested to use strcpy_s because in addition to the destination and source arguments, it has an additional argument for the size of the destination buffer to avoid overflow. But this is still probably the fastest way to copy over a string if you are using char arrays/pointers.
Example:
char *srcString = "abcd";
char destString[256];
strcpy_s(destString, 256, srcString);