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

标签 c++ arrays memcpy this-pointer

我目前正在用 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/

相关文章:

php - 数组内的foreach循环

Javascript 变量相互影响

php - 在一次调用中将多个值添加到 PHP 中的关联数组

c - 数据复制方法直接分配与c中的memcpy

c++ - 矩阵运算符*= c++ 返回错误

c++ - 为什么 boost::bind 与前向声明不兼容?

c - 嵌套结构中的 Memcpy

c++ - 将结构复制到不同的结构

c++ - 编译时对 boost::system::system_category() 的 undefined reference

c++ - 键入以存储高度精确的小数 < 1