Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stop r-value invoking move assignment C++ 11

Tags:

c++

c++11

Consider a simple C++ class that I do not want to modify:

class foo {};

Then if I do the following I will invoke the move assignment operator:

foo f{};

f = foo{};

Is there a way to invoke copy assignment without modifying foo or using an intermediate g like this:

foo f{};
foo g{};
f = g;

Almost as if there were std::dont_move!

like image 745
keith Avatar asked Dec 24 '22 20:12

keith


2 Answers

std::dont_move() is easy to implement by yourself:

template <typename T>
const T& force_copy(T&& v)
{
    return v;
}

See usage example

like image 52
Rost Avatar answered Jan 05 '23 04:01

Rost


You can write:

f = static_cast<foo const&>(foo{});
like image 41
M.M Avatar answered Jan 05 '23 02:01

M.M