我可以对我之前新建的指针使用 memcpy 吗?

Could I use memcpy to the pointer which I new it before?

本文关键字:memcpy 指针 新建 我可以      更新时间:2023-10-16

例如,我尝试编写自己的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,但我可以在指针startend之间复制所有我的内容

为什么?非常感谢。

第一个问题是这仅适用于简单类型(阅读 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++的方法。

希望这有帮助!