【发布时间】:2010-12-31 12:18:54
【问题描述】:
我正在做一些维护工作,遇到了类似以下情况:
std::string s;
s.resize( strLength );
// strLength is a size_t with the length of a C string in it.
memcpy( &s[0], str, strLength );
我知道使用 &s[0] 如果它是 std::vector 是安全的,但这是对 std::string 的安全使用吗?
【问题讨论】:
-
使用 &s[0] 是可以的, memcpy() 可以说不那么好。为什么不简单地进行赋值,或者使用字符串的 assign() 成员函数?
-
@Neil Butterworth,这就是我在查看这段代码时问自己的问题...... ;)
-
随着C++编程经验的积累,你会越来越避免使用
memset和memcpy,并学习其中的道理。这是一个可以增加您体验的内容。
标签: c++ memcpy stdstring c++03