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

Categories

0 votes
226 views
in Technique[技术] by (71.8m points)

c++ - Constructors : difference between defaulting and delegating a parameter

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

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

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...