How to make sure an object will really be moved from?

ぃ、小莉子 提交于 2019-12-24 01:15:00

问题


Consider the following code, which tries to move-construct a shared_ptr, but due to a mistake appears to copy-construct it:

#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
}

Here the fact that due to x being const, y was copy-constructed instead of move-construction will only be detected at runtime. Is there any way to make sure move really occurs, at compile time?


回答1:


You could write a checker to see if an expression could be moved from:

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

Then you can static_assert that std::move(x) can be moved from:

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");
}

I'm not really sure how useful this is in practice though. You still can't guarantee that something will truly be moved from unless you know what the constructors of the class do.



来源:https://stackoverflow.com/questions/35792881/how-to-make-sure-an-object-will-really-be-moved-from

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!