如何确保对象真的会被移动



考虑以下代码,它尝试移动构造一个shared_ptr,但由于错误似乎复制构造它:

#include <utility>
#include <cassert>
#include <memory>
int main()
{
    const auto x=std::make_shared<int>(4325); // can't be moved from
    const std::shared_ptr<int> y(std::move(x)); // silently copy-constructs
    assert(x==nullptr); // fails
}

这里由于xconsty是复制构造而不是移动构造的事实只会在运行时被检测到。有没有办法确保在编译时真正发生移动?

您可以编写一个检查器来查看是否可以从以下位置移动表达式:

template <typename T>
constexpr bool can_be_moved (T&&) {
    return !std::is_reference<T>{} && !std::is_const<T>{};    
}

然后,您可以static_assert可以从以下位置移动std::move(x)

int main()
{
    const auto x=std::make_shared<int>(4325);
    const std::shared_ptr<int> y(std::move(x));
    static_assert(can_be_moved(std::move(x)), "x must be able to be moved from");
}

不过,我不确定这在实践中有多大用处。你仍然不能保证某些东西会真正被移动,除非你知道类的构造函数做什么。

相关内容

最新更新