Does the move constructor implicitly work for member variables?

Why is this: (vs2010) moving a vector inside a class?

#include <vector>

class MoveTest
{
public:
    std::vector<int> m_things;
};

int _tmain(int argc, _TCHAR* argv[])
{
    MoveTest m;
    m.m_things.push_back(12);

    MoveTest m2 = std::move(m);
    // std::vector has been copied, not moved

    return 0;
}

Does this mean that every class that uses std :: vector (and other movable classes) must have an explicit move constructor and assignment?

+3
source share
4 answers

With a fully compatible C ++ 0x compiler, your class will have an implicit move constructor that moves elements, as well as an implicit copy constructor. In this example, the implicit move constructor will be used.

MSVC2010 , , . , , , :

class MoveTest
{
public:
    std::vector<int> m_things;

    MoveTest()
    {}

    MoveTest(MoveTest&& other):
        m_things(std::move(other.m_things))
    {}

    MoveTest(MoveTest const& other):
        m_things(other.m_things)
    {}

    MoveTest& operator=(MoveTest&& other)
    {
        MoveTest temp(std::move(other));
        std::swap(*this,temp);
        return *this;
    }

    MoveTest& operator=(MoveTest const& other)
    {
        if(&other!=this)
        {
            MoveTest temp(other);
            std::swap(*this,temp);
        }
        return *this;
    }

};
+7

, , vs2010,

:

X , ,

  • X ,
  • X ,
  • X ,
  • X
  • .

.

, , !

, . , ; (8.4). .

:

, . , ; default (8.4). , .

: 3 5. 5 ( ), (, , ) 5:

  • move constructor
+9

MoveTest , .

-.: -)

There are times when the C ++ 11-conform compiler will generate a default move constructor, but I'm not sure where the final rules ended (very late changes occurred). VS2010 is too old to learn about this.

+2
source

VS2010 does not have implicit move constructors. You will have to explicitly write one.

+1
source

All Articles