这个指针指向的内存区域,使用memcpy操作是否安全?

2026-04-16 19:262阅读0评论SEO教程
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计335个文字,预计阅读时间需要2分钟。

这个指针指向的内存区域,使用memcpy操作是否安全?

我在C++中编写自己的字符串实现。为了练习,我有一个复制构造函数:`string_baseT(const string_baseT obj) : len(obj.len)`。

我目前正在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中.

就像那样:

这个指针指向的内存区域,使用memcpy操作是否安全?

// "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>)); }

是否可以安全地覆盖*这样的数据?或者这会产生任何问题吗?

提前致谢!

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

If the objects are not TriviallyCopyable, the behavior of memcpy is not specified and may be undefined.

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

此外,您的复制构造函数只会生成浅拷贝(如果您需要,可能会很好,例如,应用了字符串的写时复制机制).

本文共计335个文字,预计阅读时间需要2分钟。

这个指针指向的内存区域,使用memcpy操作是否安全?

我在C++中编写自己的字符串实现。为了练习,我有一个复制构造函数:`string_baseT(const string_baseT obj) : len(obj.len)`。

我目前正在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中.

就像那样:

这个指针指向的内存区域,使用memcpy操作是否安全?

// "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>)); }

是否可以安全地覆盖*这样的数据?或者这会产生任何问题吗?

提前致谢!

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

If the objects are not TriviallyCopyable, the behavior of memcpy is not specified and may be undefined.

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

此外,您的复制构造函数只会生成浅拷贝(如果您需要,可能会很好,例如,应用了字符串的写时复制机制).