我目前正在用 C++ 编写自己的字符串实现。 (只是为了锻炼)。
但是,我目前有这个复制构造函数:
// "obj" has the same type of *this, it's just another string object
string_base<T>(const string_base<T> &obj)
: len(obj.length()), cap(obj.capacity()) {
raw_data = new T[cap];
for (unsigned i = 0; i < cap; i++)
raw_data[i] = obj.data()[i];
raw_data[len] = 0x00;
}
我想稍微提高性能。所以我想到了使用 memcpy()
将 obj
复制到 *this
中。
就这样:
// "obj" has the same type of *this, it's just another string object
string_base<T>(const string_base<T> &obj) {
memcpy(this, &obj, sizeof(string_base<T>));
}
这样覆盖*this
的数据安全吗?或者这会产生什么问题吗?
提前致谢!
最佳答案
不,这不安全。来自 cppreference.com:
If the objects are not
TriviallyCopyable
, the behavior ofmemcpy
is not specified and may be undefined.
您的类不是TriviallyCopyable
,因为它的复制构造函数是用户提供的。
此外,您的复制构造函数只会制作浅拷贝(如果您愿意,这可能没问题,例如,对您的字符串应用写时复制机制)。
关于c++ - 使用此指针的 memcpy 安全吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50907271/