I was wondering in which situations I still need to use const references in parameters since C++11. I don't fully understand move semantics but I think this is a legit question. This question is meant for only the situations where a const reference replaces a copy being made while it is only needed to "read" the value (e.g. usage of const member functions).
Normally I would write a (member)function like this:
#include <vector>
template<class T>
class Vector {
std::vector<T> _impl;
public:
void add(const T& value) {
_impl.push_back(value);
}
};
But I'm thinking that it's safe to assume that to compiler would optimize it using move semantics if I write it like this and class T
ofcourse implements a move constructor:
#include <vector>
template<class T>
class Vector {
std::vector<T> _impl;
public:
void add(T value) {
_impl.push_back(value);
}
};
Am I right? If so, is it safe to assume it can be used in any situation? If not, I would like to know which. This would make life much easier since I wouldn't have to implement an class specialization for fundamental types for example, besides it looks much cleaner.
vector::push_back
makes copies. You're looking foremplace_back
. – Delilavector
. I'm wondering if the compiler is able to eliminate the second copy through move semantics (see second example). – Rodrick