Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explicitly select copy assignment

Tags:

c++

c++11

One possible way is to write your own copy to bind the object to an lvalue reference:

template <class T>
constexpr T& copy(T&& t) noexcept
{
    return t;
}

And you can test it this way:

test = copy(a);
test = copy(3);
test = copy(std::move(a));

You may put this function in your own namespace to keep things clean. You may also choose a better name for it.


To address fear of lifetime issue, here is some considerations:

  • This copy function takes a reference and returns the same reference immediately. It implies that the caller is responsible for controlling the lifetime.
  • Lifetime of a temporary object persists until the end of the statement. This makes the object persists long enough to be passed into the left hand side of =.

You can static_cast to const int&:

test = static_cast<const int&>(3);