首页 > 解决方案 > 带有这个指针的 memcpy 安全吗?

问题描述

我目前正在用 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?或者这可能会产生任何问题?

提前致谢!

标签: c++arraysmemcpythis-pointer

解决方案


不,这不安全。来自 cppreference.com:

如果对象不是TriviallyCopyable,则 的行为memcpy未指定并且可能未定义。

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


此外,您的复制构造函数只会制作浅层副本(如果您愿意,这可能很好,例如,与您的字符串一起应用的写时复制机制)。


推荐阅读