Ruslan
Ruslan

Reputation: 19130

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

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?

Upvotes: 2

Views: 156

Answers (1)

TartanLlama
TartanLlama

Reputation: 65620

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.

Upvotes: 3

Related Questions