为什么在没有std::move的情况下不调用move构造函数

Why move constructor does not called without std::move?

本文关键字:move 情况下 调用 构造函数 std 为什么      更新时间:2023-10-16

我有这样的代码:

SomeType::SomeType(std::vector<Item>&& container, const float someOtherPArameter)
    : internal_container(std::move(container))
{
    // some code here
}

有人能向我解释一下为什么move构造函数不调用没有"std::move"的"internal_container"吗?

每当从相同类型的xvalue初始化对象时,都会调用move构造函数。您可以通过调用std::move(x)来创建该xvalue。将参数声明为右值引用不会自动使其成为xvalue

因为

SomeType::SomeType(std::vector<Item>&& container, const float someOtherPArameter)
    : internal_container(container)
{
    // the parameter container is in scope here
}

如果在构造函数体内部,对参数container的访问发现了一个moved-from对象,那将是非常令人惊讶的。(它也会破坏在C++03中完全有效的代码)

这就是为什么您必须明确启用move。