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";
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With