c++ - Constructing a pair with an rvalue -


in this:

    vector<pair<string,int>> vp;     string s;     int i;     while(cin>>s>>i) vp.push_back({s,i}); 

i'm curious last line. pair constructed in call push_back, therefore moved, not copied, correct?

if had instead been written this:

    vector<pair<string,int>> vp;     string s= ...;     int i= ...;     pair<string,int> p{s,i};     vp.push_back(p); 

while construction of pair involves same resources, pair named, p, therefore no longer rvalue , therefore move semantics no longer used, , therefore pass value, causing copy made, right?

this implies me possible, constructing objects inside arg lists performance improvement; can verify?

the pair constructed in call push_back, therefore moved, not copied, correct?

the temporary pair constructed , bound rvalue reference argument of push_back. moved argument vector.

vp.push_back({s,i}); 

is equivalent to:

vp.push_back(std::pair<std::string, int>{s, i}); 

which equivalent to:

std::pair<std::string, int> p{s, i}; vp.push_back(std::move(p)); 

you don't need temporary use rvalue reference overload.

your second code example:

pair<string,int> p{s,i}; vp.push_back(p); 

does copy instead of move, yes. note either way, we're still copying s pair (either temporary or p). better approach move s temporary well:

vp.push_back({std::move(s), i}); 

or not have intermediate pair begin with:

vp.emplace_back(std::move(s), i); 

this implies me possible, constructing objects inside arg lists performance improvement; can verify?

moving performance improvement, can std::move() argument function - doesn't need temporary. constructing inside arg list affects when moved-from object's destructor gets called, nothing more.


Comments

Popular posts from this blog

java - nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet Hibernate+SpringMVC -

sql - Postgresql tables exists, but getting "relation does not exist" when querying -

asp.net mvc - breakpoint on javascript in CSHTML? -