我可以对我之前新建的指针使用 memcpy 吗?
Could I use memcpy to the pointer which I new it before?
例如,我尝试编写自己的vector
,所以我只是像这样编写其assign
函数
template <typename T>
void Vector<T> :: assign(T *start, T *end)
{
if (end - start > _capacity)
{
resize(end - start);
}
_size = end - start;
delete []ptr;
ptr = new T[_capacity];
memcpy(ptr, start, end - start);
}
我之前有新的指针ptr
,但我可以在指针start
和end
之间复制所有我的内容
为什么?非常感谢。
第一个问题是这仅适用于简单类型(阅读 POD)。
任何带有构造函数/析构函数的东西都需要调用它们。
其次,这不是例外安全。
它甚至没有提供基本保障让一个孤单的强力保障。
在修改对象之前,您需要执行所有异常不安全的工作。这意味着new
必须在修改对象之前完成(绝对是在自由对象之前)。否则,您可能会抛出使对象处于无效状态(这可能看起来不错,但是如果您捕获异常并继续,您现在有一个包含指向释放内存的指针的对象怎么办)。
因此,即使您使用std::copy()
您仍然做错了事情。
我个人认为 std::copy() 的建议是一个红鲱鱼。它将正确复制数据,但您的方法仍然写得不好。您需要在副本上使用扭曲并交换 idium。
template <typename T>
void Vector<T> :: assign(T *start, T *end)
{
Vector<T> tmp(start, end); // construct a temp object that allocates the memory.
swap(tmp); // Swap the current object and the tmp objects data.
// When the tmp object goes out of scope it will delete
// what was the current objects data
}
以这种方式重用指针是完全可以的,但在这里使用 memcpy 是不安全的,因为你不知道 T 是什么类型。 如果 T 是字符串或矢量等对象类型,则会导致未定义的行为。
要解决此问题,请将该行更改为
std::copy(start, end, ptr);
这是安全,C++的方法。
希望这有帮助!
相关文章:
- 1d 智能指针不适用于语法 (*)++
- 在C#中处理C++指针而不使用unsafe的最佳方法
- 为什么使用 "this" 指针调用派生成员函数?
- 函数向量_指针有不同的原型,我可以构建一个吗
- 从向量到空指针的 memcpy(反之亦然)不起作用
- 由于指针算法错误,代码在 memcpy 中崩溃
- memcpy是否取决于源指针和目标指针的类型
- 使用 aligned_malloc 和 memcpy 多次将结构复制到指针
- memcpy指向炭缓冲区的指针
- 可以使用memcpy()来复制包含指针的结构吗
- Memcpy崩溃,具体取决于指针类型
- 用memcpy c 读取并写入指针功能
- 我可以对我之前新建的指针使用 memcpy 吗?
- 使用memcpy将数据复制到结构的成员,并给出指向结构的双指针
- 使用Memcpy扩展指针数组的大小
- Memcpy字符指针
- 如何获得指向memcpy成员变量的指针
- 使用 'memcpy()' 为指针分配地址
- 将模板指针传递给 memcpy
- 可以删除使用memcpy()复制的类指针吗?