C++ 中 strcpy 的替代方案
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4751446/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Alternative of strcpy in c++
提问by Aerus
In C i used strcpy
to make a deep copyof a string, but is it still 'fine'to use strcpy
in C++ or are there better alternatives which i should use instead ?
在 C 中,我曾经strcpy
制作一个字符串的深层副本,但是在 C++ 中使用它仍然“很好”strcpy
还是有更好的替代方案我应该使用?
回答by Zac Howland
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()
;
因此,如果您真的想模仿 的行为strcpy
,则需要使用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:
应该注意的是,C++11 标准明确禁止在std::string
以前的许多实现中使用的常见的写时复制模式。因此,不再允许引用计数字符串,以下内容将创建一个副本:
std::string a = "Hello.";
std::string b;
b = a; // C++11 forces this to be a copy as well
回答by kynnysmatto
In C++ the easiest way is usually to use the std::string class instead of char*.
在 C++ 中,最简单的方法通常是使用 std::string 类而不是 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.
“b = a;”这一行 做你通常用 strcpy 做的同样的事情。
回答by SuperElectric
If you're using c++ strings, just use the copy constructor:
如果您使用的是 C++ 字符串,只需使用复制构造函数:
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.
如果您必须使用 c 样式的字符串(即以空字符结尾的字符数组),那么是的,只需使用 strcpy,或者作为更安全的替代方法,strncpy。
回答by Nick Banks
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.
建议您使用 strcpy_s ,因为除了目标和源参数之外,它还有一个用于目标缓冲区大小的附加参数,以避免溢出。但是,如果您使用字符数组/指针,这可能仍然是复制字符串的最快方法。
Example:
例子:
char *srcString = "abcd";
char destString[256];
strcpy_s(destString, 256, srcString);