gpt4 book ai didi

c++ - 使用此指针的 memcpy 安全吗?

转载 作者:太空狗 更新时间:2023-10-29 20:20:29 29 4
gpt4 key购买 nike

我目前正在用 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 of memcpy is not specified and may be undefined.

您的类不是TriviallyCopyable,因为它的复制构造函数是用户提供的。


此外,您的复制构造函数只会制作浅拷贝(如果您愿意,这可能没问题,例如,对您的字符串应用写时复制机制)。

关于c++ - 使用此指针的 memcpy 安全吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50907271/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com