How this push_back overload implemented?
void push_back( T&& value );
Or maybe one possible implementation?
How this push_back overload implemented?
void push_back( T&& value );
Or maybe one possible implementation?
One possible implementation:
template <typename T, typename Allocator>
void
vector<T, Allocator>::push_back(T&& _element)
{
if (size() == capacity()) reallocate(capacity() * 2);
construct(data()[size()], std::move(_element));
++size_val;
update_vector();
}
construct() would call T::T(T&&) if there is one. Otherwise it would call T::T(const T&).
See https://en.cppreference.com and search construct for more information
A very simple implementation would be:
template <typename T, typename Allocator>
void vector<T, Allocator>::push_back(T&& _element)
{
emplace_back(std::move(_element));
}
If the value type T
has a move constructor (that is, T::T(T&&)
), doing it this way can be more efficient than using its copy constructor. A std::vector
does require its value type to be copy-constructible, so this will use the copy constructor if there is no move constructor.
A common case where this makes a difference is when a class contains a pointer to a large buffer or structure. If we need a copy initialized to the same data that we can modify, and the original has to remain valid, we have to make an expensive deep copy. On the other hand, when we know the source is a temporary that is about to be thrown away, we can just swap its contents with those of an empty object. That lets us re-use the same memory with no reallocations or deep copies of its contents.