Constructors : difference between defaulting and d

2019-01-18 03:21发布

问题:

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 ?

回答1:

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.



标签: c++ std c++14