std::vector::push_back(constT& value)
requires the type T to be CopyInsertable according to this .
However, compiling the following program with failes (clang, GCC, Visual; both without c++11) unless I provide a public assignment operator.
#include <vector>
class A {
A& operator= (const A& rhs); //private !!
};
int main() {
std::vector<A> v;
A a;
v.push_back(a);
}
Why do I need to provide this assignment operator, I was under the impression that the copy construct was enough.
P.S. I could not find the place in the standard where this is defined, so if you could point to the reference, I would be most grateful
vector::push_back() push_back() function is used to push elements into a vector from the back. The new value is inserted into the vector at the end, after the current last element and the container size is increased by 1.
Yes, std::vector<T>::push_back() creates a copy of the argument and stores it in the vector.
The push_back() function is used to insert an element at the end of a vector.
You should definitely use emplace_back when you need its particular set of skills — for example, emplace_back is your only option when dealing with a deque<mutex> or other non-movable type — but push_back is the appropriate default. One reason is that emplace_back is more work for the compiler.
vector::push_back() and vector::pop_back() in C++ STL. Vectors are same as dynamic arrays with the ability to resize itself automatically when an element is inserted or deleted, with their storage being handled automatically by the container. vector::push_back() push_back() function is used to push elements into a vector from the back.
If T 's move constructor is not noexcept and T is not CopyInsertable into *this, vector will use the throwing move constructor. If it throws, the guarantee is waived and the effects are unspecified.
vector::push_back () push_back () function is used to push elements into a vector from the back. The new value is inserted into the vector at the end, after the current last element and the container size is increased by 1.
Some implementations also throw std::length_error when push_back causes a reallocation that would exceed max_size, due to implicitly calling an equivalent of reserve (size ()+1) .
The reference you quote applies to C++11. However, the C++03 standard has stricter requirements on types that can be stored in containers:
23.1 Container requirements [lib.container.requirements]
...
The type of objects stored in these components must meet the requirements of CopyConstructible types (20.1.3), and the additional requirements of Assignable types.
(emphasis mine.) These requirements have been greatly relaxed in C++11, and are usually expressed in terms of the specific operations performed on containers. In that standard, your code would be valid, since the only requirement would be that A
be CopyInsertable
.
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