Alternative of strcpy in c++

痞子三分冷 提交于 2019-12-05 03:00:49

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.

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'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.

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);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!