[Development] QVector now has rvalue push_back (was: Re: HEADS UP: potential trouble from a recent QVector change)
Marc Mutz
marc.mutz at kdab.com
Tue Jul 21 20:36:09 CEST 2015
On Tuesday 21 July 2015 17:53:55 Thiago Macieira wrote:
> I'm asking why one of the two would be better than the other if I'm trying
> to add a single T to std::vector<T>. You've explained that emplace_back
> is efficient, but you haven't said whether push_back is as efficient, more
> efficient or less efficient than that.
>
> emplace_back will do perfect forwarding without copy direct into the
> vector. Does push_back do the same?
Best explained with some code:
template <typename T, [...]>
class vector {
T *m_begin, *m_end, *m_capacity;
// ...
public:
void push_back(const T &t) {
ensureCapacity(size() + 1);
new (m_end) T(t); // copy-construct from t
++m_end;
}
void push_back(T &&t) {
ensureCapacity(size() + 1);
new (m_end) T(std::move(t)); // move-construct from t
++m_end;
}
template <typename ...Args>
void emplace_back(Args ...&&args) {
ensureCapacity(size() + 1);
new (m_end) T(std::forward<Args>(args)...); // construct with args
++m_end;
}
};
--
Marc Mutz <marc.mutz at kdab.com> | Senior Software Engineer
KDAB (Deutschland) GmbH & Co.KG, a KDAB Group Company
Tel: +49-30-521325470
KDAB - The Qt Experts
More information about the Development
mailing list