Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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 ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
233 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...