Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't emplace/_front/_back return a reference?

When using std::vectors, std::lists (or other STL containers), I happen to often write this, for code shortness (rather than putting explicit vec[index] every time) and memory allocation efficiency (avoiding a copy/move), and I suppose I'm not the only one to do such:

std::vector<A> vec;
vec.emplace_back();
A &element = vec[vec.size()-1];
element.prop = "value";

Why doesn't STL containers' emplace, emplace_back and emplace_front methods return a T&? It would allow one to write simply this rather than using a shady vec.size()-1:

std::vector<A> vec;
A &element = vec.emplace_back();
element.prop = "value";
like image 586
ElementW Avatar asked Jun 26 '14 14:06

ElementW


2 Answers

This has been fixed in C++17. Your example

std::vector<A> vec;
A &element = vec.emplace_back();
element.prop = "value";

is valid C++17 code.

like image 64
Johan Råde Avatar answered Nov 30 '22 22:11

Johan Råde


You have member methods to access those objects, since you know where they have been inserted. Namely front() and back().

Some other functions (e.g. map::insert) would return an iterator because you don't know how to access the inserted element in constant time. In the case of emplace, you do know.

Another reason for not returning anything might be performance (most of the time you would not use the returned value). And in C++ , you pay for what you use.

like image 25
quantdev Avatar answered Dec 01 '22 00:12

quantdev