使用指针向量实现移动构造函数

Implement move constructor with vector of pointers

我的 class:

中有指针向量
std::vector<Customer *> customers

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

我的移动构造函数:

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

the problam is that I don't know if it will clear the old vector values.

vector 在移动后保证为空。

customers=std::move(other.customers);

与其默认构造成员然后移动赋值,不如直接在成员初始化列表中移动构造成员:

OpenTable::OpenTable(OpenTable&& other) : ..., customers(std::move(other.customers))

尽管如此,您的构造函数看起来很像与隐式移动构造函数没有任何不同,因此您可以改用:

OpenTable::OpenTable(OpenTable&&) = default;

更好的是,根据您的其余部分 class,移动构造函数可能会隐式声明,因此您甚至可能不需要默认声明。

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

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

不过,也应该说:

I have vector of pointers in my class:

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

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