The explicit
keyword is recommended for all most constructors which can be called with one argument, except for copy constructors.
For copy constructors, it has an use (to forbid implicit copying via function call, return, etc), but it's not what's usually wanted.
What about move constructors? Is there any reasonable use case to make them explicit? What's the good practice here?
Explicit isn't recommended for all one-argument constructors, but it is recommended for most. Move constructors are not on that list.
Implicitly-defined move constructor For non-union class types (class and struct), the move constructor performs full member-wise move of the object's bases and non-static members, in their initialization order, using direct initialization with an xvalue argument.
A move constructor allows the resources owned by an rvalue object to be moved into an lvalue without creating its copy. An rvalue is an expression that does not have any memory address, and an lvalue is an expression with a memory address.
A move constructor enables the resources owned by an rvalue object to be moved into an lvalue without copying. For more information about move semantics, see Rvalue Reference Declarator: &&. This topic builds upon the following C++ class, MemoryBlock , which manages a memory buffer.
An explicit
move constructors can affect compatibility with e.g. Standard algorithms. For instance, std::swap<T>
requires that T
be MoveConstructible. In turn, MoveConstructible is specified in terms of an expression, namely T u = rv;
(where rv
is an rvalue of type T
).
If there is neither a non-explicit copy constructor nor a non-explicit move constructor for a given type then T u = rv;
is invalid and that type can't be used with std::swap
. (In this particular instance however it is possible to specialize std::swap
to provide the desired functionality, e.g. by using T u(rv);
).
Put more simply, an explicit
move or copy constructor defies expectations and can't be used as well with generic code.
Some other parts of the Standard library that put a MoveConstructible requirement:
unique_ptr<T, D>
bind
(all the decayed types that are passed are concerned)thread
, async
, call_once
(all specified in terms of call wrappers)sort
, stable_sort
, nth_element
, sort_heap
You probably want an implicit move constructor for the majority of uses. They generally fall into the same categories as copy constructors. Explicit isn't recommended for all one-argument constructors, but it is recommended for most. Move constructors are not on that list.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With