chrise
chrise

Reputation: 4253

c++ (why) does move constructor delete operator=

I have a vector with structs

Struct S {
    S( double a, double b ) : a_(a), b_(b) {}
    double a_;
    double b_;
    S(S&&) = default;   //ADDED
}

and I use emplace back to add instances of s to the vector

v.emplace_back( x, y );

Since it doesn't seem to be guaranteed that compilers will add a move constructor, I thought there is no harm in adding a default move constructor, so I added the line commented as ADDED. However, this seemed to have disabled the operator= as I get the compile error

/opt/rh/devtoolset-3/root/usr/include/c++/4.9.2/bits/stl_algo.h:868: error: use of deleted function ‘S& S::operator=(const S&)’
         *__result = _GLIBCXX_MOVE(*__first);
                   ^

I dont understand why that is the case. Is my implementation of S(S&&) the wrong way to do it?

EDIT: The error is thrown when using erase-remove

v.erase(std::remove_if(v.begin(), v.end(), deleteIf), v.end());

Upvotes: 0

Views: 148

Answers (2)

RichS
RichS

Reputation: 550

Some older implementations of STL containers use the assignment operator when they resize the underlying containers. To resize, they allocate memory, default construct the initial objects, copy the objects over to the new container by using the assignment operator, and then release the previous objects.

On a related topic, if you are going to make an object Move-Constructible, you should also make it Move-Assignable.

Since the only data members in your struct are double's - primitive types that don't allocate resources - you don't need a move constructor for this struct.

Upvotes: 2

David Scarlett
David Scarlett

Reputation: 3341

A default copy assignment operator will be automatically provided (performing a memberwise copy) unless the class declares a copy assignment operator, deletes the copy assignment operator, or declares a move operation. The reason for this is that the compiler assumes that if you declare any move operation, it is likely that your class holds data which should not be copied, and so it forces you to implement the copy assignment operator yourself, in an attempt to enforce the Rule of Five.

There's an excellent chart showing when default constructors and assignment operators are provided in this slideshow, slide 30.

Upvotes: 3

Related Questions