Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does std::vector have two assignment operators?

Since 2011, we have both copy and move assignment. However, this answer argues quite convincingly that, for resource managing classes, one needs only one assignment operator. For std::vector, for example, this would look like

vector& vector::operator=(vector other)
{
  swap(other);
  return*this;
}

The important point here is that the argument is taken by value. This means that at the moment the function body proper is entered, much of the work has already been done by the construction of other (by move constructor if possible, otherwise by copy constructor). Hence, this automatically implements both copy and move assignment correctly.

If this is correct, why is (according to this documentation at least) std::vector not implemented in this way?


edit to explain how this works. Consider what happens to other in above code in the following examples

void foo(std::vector<bar> &&x)
{
  auto y=x;             // other is copy constructed
  auto z=std::move(x);  // other is move constructed, no copy is ever made.
  // ...
}
like image 919
Walter Avatar asked Nov 20 '15 23:11

Walter


People also ask

Does STD Vector assign allocate?

As mentioned above, std::vector is a templated class that represents dynamic arrays. std::vector typically allocates memory on the heap (unless you override this behavior with your own allocator).

Why do we overload assignment operator?

The overloading assignment operator can be used to create an object just like the copy constructor. If a new object does not have to be created before the copying occurs, the assignment operator is used, and if the object is created then the copy constructor will come into the picture.

What is an std :: vector?

1) std::vector is a sequence container that encapsulates dynamic size arrays. 2) std::pmr::vector is an alias template that uses a polymorphic allocator. The elements are stored contiguously, which means that elements can be accessed not only through iterators, but also using offsets to regular pointers to elements.

Is == A assignment operator?

The “=” is an assignment operator is used to assign the value on the right to the variable on the left. The '==' operator checks whether the two given operands are equal or not. If so, it returns true.


1 Answers

If the element type is nothrow copyable, or the container does not honor the strong exception guarantee, then a copy-assignment operator can avoid allocation in the case where the destination object has sufficient capacity:

vector& operator=(vector const& src)
{
    clear();
    reserve(src.size());  // no allocation if capacity() >= src.size()
    uninitialized_copy_n(src.data(), src.size(), dst.data());
    m_size = src.size();
}
like image 173
ecatmur Avatar answered Nov 08 '22 19:11

ecatmur