Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constructors : difference between defaulting and delegating a parameter

Tags:

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 ?

like image 939
Nelfeal Avatar asked Sep 05 '14 22:09

Nelfeal


People also ask

What is the difference between default constructor and default argument constructor?

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.

What are delegating constructors?

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.

Can a class have a constructor with default parameters?

Yes, a constructor can contain default argument with default values for an object.

What is default and parameterized constructor in C++?

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.


1 Answers

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 Allocators 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.

like image 103
T.C. Avatar answered Nov 10 '22 13:11

T.C.