gpt4 book ai didi

c++ - 使用指针 vector 实现移动构造函数

转载 作者:太空宇宙 更新时间:2023-11-04 15:57:36 26 4
gpt4 key购买 nike

我的课上有指针 vector :

std::vector<Customer *> customers

现在我想实现移动构造函数。我发现我可以使用 std::vectorstd::move。问题是我不知道它是否会清除旧的 vector 值。如果有人可以向我解释一下。

我的移动构造函数:

OpenTable::OpenTable(OpenTable&& other) : BaseAction(), tableId(other.tableId)
{
customers=std::move(other.customers);
}

最佳答案

你的移动构造函数会做你想做的,不需要清除任何东西

std::move()std::vector 开始后,旧 vector 将有 0 个元素,并且没有为其分配动态内存。新构造的 vector 带走了那段内存。无需清除任何元素。

但是,还应该说:

I have vector of pointers in my class:

这是一个错误...我们不再使用 C++98。原始指针不表示谁拥有内存,也不表示地址处对象的生命周期。现在,您可能做对了,但也可能做错了。那么你的代码的 future 维护者呢?最好不要碰运气:使用 smart pointer反而。或者 - 只需将实际对象放在 vector 中。正如评论所暗示的那样,如果您移动而不是复制 vector ,则不会为相同的对象制作额外的拷贝。

有关这一点的更多信息,请参阅 Resource Management section of the C++ Core Programming Guidelines .

关于c++ - 使用指针 vector 实现移动构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53283796/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com