Today, I stumbled upon these standard declarations of std::vector
constructors :
// until C++14
explicit vector( const Allocator& alloc = Allocator() );
// since C++14
vector() : vector( Allocator() ) {}
explicit vector( const Allocator& alloc );
This change can be seen in most of standard containers. A slightly different exemple is std::set
:
// until C++14
explicit set( const Compare& comp = Compare(),
const Allocator& alloc = Allocator() );
// since C++14
set() : set( Compare() ) {}
explicit set( const Compare& comp,
const Allocator& alloc = Allocator() );
What is the difference between the two patterns and what are their (dis)advantages ?
Are they strictly equivalent - does the compiler generate something similar to the second from the first ?
A default constructor is a 0 argument constructor which contains a no-argument call to the super class constructor. To assign default values to the newly created objects is the main responsibility of default constructor.
A delegating constructor can be a target constructor of another delegating constructor, thus forming a delegating chain. The first constructor invoked in the construction of an object is called principal constructor . A constructor cannot delegate to itself directly or indirectly.
Yes, a constructor can contain default argument with default values for an object.
The default constructor is a constructor that the compiler automatically generates in the absence of any programmer-defined constructors. Conversely, the parameterized constructor is a constructor that the programmer creates with one or more parameters to initialize the instance variables of a class.
The difference is that
explicit vector( const Allocator& alloc = Allocator() );
is explicit
even for the case where the default argument is used, while
vector() : vector( Allocator() ) {}
is not. (The explicit
in the first case is necessary to prevent Allocator
s from being implicitly convertible to a vector
.)
Which means that you can write
std::vector<int> f() { return {}; }
or
std::vector<int> vec = {};
in the second case but not the first.
See LWG issue 2193.
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