c++ - 带有这个指针的 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
?或者这可能会产生任何问题?
提前致谢!
解决方案
不,这不安全。来自 cppreference.com:
如果对象不是
TriviallyCopyable
,则 的行为memcpy
未指定并且可能未定义。
您的类 is not TriviallyCopyable
,因为它的复制构造函数是用户提供的。
此外,您的复制构造函数只会制作浅层副本(如果您愿意,这可能很好,例如,与您的字符串一起应用的写时复制机制)。
推荐阅读
- sql - 从给定所有者的所有记录中计算记录的百分比
- c++ - 为什么到处都使用套接字指针而不是套接字实例?
- node.js - Mongodb 查询不显示预期结果
- python - 使用 Python 进行网页抓取 - 空白返回
- elasticsearch - 如何检查 kubernetes 集群中状态集的重启原因
- webstorm - WebdriverIO 5 - 'browser.$(...).click 不是函数' 错误
- swift - 如何使用 swiftUI 沿自定义路径移动视图/形状?
- android - 将两个 RxJava 请求转换为一个请求
- python - 如何在具有其他特征(如 OpenCV 中的划痕)的灰度图像中提取文本
- mysql - Laravel - 如何立即更新表记录保存在其中