c – 这个指针的memcpy是否安全?
发布时间:2020-12-16 09:21:02 所属栏目:百科 来源:网络整理
导读:我目前正在C中编写自己的字符串实现. (只是为了锻炼). 但是,我目前有这个拷贝构造函数: // "obj" has the same type of *this,it's just another string objectstring_baseT(const string_baseT obj) : len(obj.length()),cap(obj.capacity()) { raw_data =
我目前正在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>)); } 是否可以安全地覆盖*这样的数据?或者这会产生任何问题吗? 提前致谢! 解决方法
不,这不安全.来自cppreference.com:
您的类不是TriviallyCopyable,因为它的复制构造函数是用户提供的. 此外,您的复制构造函数只会生成浅拷贝(如果您需要,可能会很好,例如,应用了字符串的写时复制机制). (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |