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
708 views
in Technique[技术] by (71.8m points)

c++ - Calling std::map::emplace() and avoiding unnecessary constructions

I have a std::map whose keys are std::string and values are my own defined type.

Let's suppose I have the following code:

std::map<std::string, MyType> mymap;
std::string str1("test");
MyType value(pars); //I want value to be moved

mymap.emplace(std::make_pair(str1, std::move(value))); //A
mymap.emplace(str, std::move(value)); //B

Assuming std::map stores pairs, I guess A would generate a further call to std::pair constructor (make_pair), followed by another call to std::pair move constructor (in-place construction with rvalue argument).

And I think B would just generate a call to std::pair constructor.

So can we say B is preferred over A in order to avoid unnecessary constructions?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

According to http://www.cplusplus.com/reference/map/map/emplace/:

Inserts a new element in the map if its key is unique. This new element is constructed in place using args as the arguments for the construction of a value_type (which is an object of a pair type) ... The element is constructed in-place by calling allocator_traits::construct with args forwarded.

So in option A, you first construct a pair which emplace will forward to the constructor (as an rvalue) for pair which will then do a move construction.

Option B forwards str and the return of std::move(value) to the constructor for pair.

So yes, option A constructs 2 pairs while option B only constructs 1.


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

...