I'm currently learning about move/copy constructors, constness and rvalues.
"Older literature" about C++ says:
"A copy constructor must take a const argument since it should be able to take temporaries/rvalues which are not modifiable"
But nowadays, with C++ 11's move constructors, we can directly handle rvalues. This brings me to the conclusion, that it's no longer mandatory to make a copy constructor take a const reference.
Is this true? (I could neither confirm nor falsify the statement with currently existing literature and community articles.) A short discussion about the pro and contras of having the copy constructor const would also be appreciated.
No, it's not true. You want your copy constructor to take a const T&
and your move constructor to take a T&&
. Why? Well think about what happens if we pass a const
rvalue. It can't bind to the T&&
, because it's not const
. It can, however, bind to the const T&
, which is able to bind to anything. If it were just a T&
instead, it wouldn't be able to, and we'd never be able to copy from const
rvalues.
To think about it in another way: the only time a move constructor is useful is if we have an rvalue (likely a temporary object) that we can steal from, which means that it must be non- const
. All the other cases must invoke the copy constructor instead. The only reference type that will bind to everything else is a const
lvalue reference.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.