C ++ Why can't I use swap for object with remote default constructor

I am trying to implement a move constructor for an object A that uses the class identifier. The class id is automatically generated and for future coding common sense, I decided to remove the default constructor when I do this.

However, when I try to use swap in move constructor A, it complains that the default constructor Id is being deleted . I thought that swap does not create any new objects, but simply replaces the addresses of these two elements.

I misunderstood it and actually created a third temporary instance of Id ??

If so, what is the best way to implement the move constructor below?

I have included a minimal example below:

class Id {

public:
    Id() = delete;
    Id(std::string id) : m_id(id) {}

private:
    std::string m_id;
};

class A {

public:
    A() = delete;
    A(Id id) : m_id(id) {}


    A(A&& other) {
        std::swap(m_id, other.m_id);
    }

private:
    Id m_id;
};

:

In constructor 'A::A(A&&)':
21:18: error: use of deleted function 'Id::Id()'
8:5: note: declared here
In file included from /usr/include/c++/4.9/bits/stl_pair.h:59:0,
                 from /usr/include/c++/4.9/bits/stl_algobase.h:64,
                 from /usr/include/c++/4.9/bits/char_traits.h:39,
                 from /usr/include/c++/4.9/ios:40,
                 from /usr/include/c++/4.9/ostream:38,
                 from /usr/include/c++/4.9/iostream:39,
                 from 2:
/usr/include/c++/4.9/bits/move.h: In instantiation of 'void std::swap(_Tp&, _Tp&) [with _Tp = A]':
34:17:   required from here
/usr/include/c++/4.9/bits/move.h:176:11: error: use of deleted function 'A& A::operator=(const A&)'
       __a = _GLIBCXX_MOVE(__b);
           ^
15:7: note: 'A& A::operator=(const A&)' is implicitly declared as deleted because 'A' declares a move constructor or move assignment operator
In file included from /usr/include/c++/4.9/bits/stl_pair.h:59:0,
                 from /usr/include/c++/4.9/bits/stl_algobase.h:64,
                 from /usr/include/c++/4.9/bits/char_traits.h:39,
                 from /usr/include/c++/4.9/ios:40,
                 from /usr/include/c++/4.9/ostream:38,
                 from /usr/include/c++/4.9/iostream:39,
                 from 2:
/usr/include/c++/4.9/bits/move.h:177:11: error: use of deleted function 'A& A::operator=(const A&)'
       __b = _GLIBCXX_MOVE(__tmp);
+4
1

swap Id, , A.

A(A&& other) {
    std::swap(m_id, other.m_id);
}

Id, A.

, Id

A(A&& other) : m_id(std::move(other.m_id))
{  }
+6

Source: https://habr.com/ru/post/1669158/


All Articles