c – 这个指针的memcpy是否安全?

c – 这个指针的memcpy是否安全?,第1张

概述我目前正在C中编写自己的字符串实现. (只是为了锻炼). 但是,我目前有这个拷贝构造函数: // "obj" has the same type of *this, it's just another string objectstring_base<T>(const string_base<T> &obj) : len(obj.length()), cap(obj.capaci 我目前正在C中编写自己的字符串实现. (只是为了锻炼).

但是,我目前有这个拷贝构造函数:

// "obj" has the same type of *this,it's just another string objectstring_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 objectstring_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,因为它的复制构造函数是用户提供的.

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

总结

以上是内存溢出为你收集整理的c – 这个指针的memcpy是否安全?全部内容,希望文章能够帮你解决c – 这个指针的memcpy是否安全?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://www.54852.com/langs/1212169.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-06-04
下一篇2022-06-04

发表评论

登录后才能评论

评论列表(0条)

    保存