Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
237 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...