4

클래스 ID를 사용하는 객체 A의 이동 생성자를 구현하려고합니다. 클래스 ID가 자동으로 생성되고 이후 코딩 작업을 할 때 기본 생성자를 삭제할 것을 선택했습니다.C++ 삭제 된 기본 생성자가있는 객체에서 스왑을 사용할 수없는 이유

그러나 A의 이동 생성자에서 스왑을 사용하려고하면 기본 생성자 Id가 삭제됩니다.. 나는 스왑이 새로운 객체를 만들지는 않았지만 두 아이템의 주소를 바꾸는 것만 같았습니다.

나는 그것을 오해하고 실제로 ID의 세 번째 임시 인스턴스를 만들고 있습니까 ??

아래에 이동 생성자를 구현하는 가장 좋은 방법은 무엇입니까?

나는 최소한의 예를 아래에 포함했다 :

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; 
}; 

컴파일러는 다음과 같은 오류 결과 : 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); 
+0

어떻게 교환 할 수있는 초기화 목록에서 Id를 초기화 한 번에 작업을 할 필요가? –

답변

6

당신 사용 swap을 문제가되지 않습니다 , 그러나 생성자는 A입니다.

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

이 기본값은 Id을 건설하고 다른 A의 회원으로 교환.

기본 생성자를 방지하려면

A(A&& other) : m_id(std::move(other.m_id)) 
{ } 
관련 문제