그래서 나는 삭제 된 복사 ctor / 할당이 있고 기본 ctor가없고 이동 ctor / 할당이있는 클래스가 있습니다.
class A {
int data_ = 0;
public:
A(const A& other) = delete;
A& operator=(const A& other) = delete;
A(int data) : data_(data) {}
~A() {}
A(A&& other) { *this = std::move(other); }
A& operator=(A&& other) {
if (this != &other) {
data_ = other.data_;
other.data_ = 0;
}
return *this;
}
};
그리고 A를 포함하는 클래스 B (기본 ctor도 없음)가 있습니다.
class B {
A a;
public:
B(const B& other) = delete;
B& operator=(const B& other) = delete;
B(int data) : a(data) {}
~B() {}
B(B&& other) { *this = std::move(other); }
B& operator=(B&& other) {
if (this != &other) {
a = std::move(other.a);
}
return *this;
}
};
이제 문제는 B 이동 ctor가 A에 대한 기본 생성자가 없다고 말했기 때문에 컴파일되지 않는다는 것입니다. 이것은 정말 성가신 일입니다. B에서 이동 ctor를 호출 할 때 새 A 인스턴스를 만들고 싶지 않습니다. 이동!
그래서 내가 할 수있는 두 가지가 있습니다.
B(B&& other) : a(std::move(other.a)) { *this = std::move(other); }
이동 할당에서 A를 다시 이동하려고합니다. "this == & other == true"이면 A를 자신에서 이동하여 이제 A 쓰레기를 만듭니다.
또 다른 방법:
기본 개인 액터를 만듭니다. B를 A의 친구로 만드십시오.하지만 그렇게 엉망이고 추악하게 들립니다.이 상황을 처리하는 가장 좋은 방법은 무엇입니까? A에 대한 기본 생성자를 만들지 않아도됩니다.
미리 감사드립니다.
해결책은 다음과 같습니다.
class A {
int data_ = 0;
public:
A(const A& other) = delete;
A& operator=(const A& other) = delete;
A(int data) : data_(data) {}
~A() {}
A(A&& other) : data_(other.data_) { other.data_ = 0; }
A& operator=(A&& other) {
if (this != &other) {
data_ = other.data_;
other.data_ = 0;
}
return *this;
}
};
class B {
A a;
public:
B(const B& other) = delete;
B& operator=(const B& other) = delete;
B(int data) : a(data) {}
~B() {}
B(B&& other) : a(std::move(a)) { }
B& operator=(B&& other) {
if (this != &other) {
a = std::move(other.a);
}
return *this;
}
};
A에는 int 만 포함되어 있기 때문에 복사본보다 성능이 좋지는 않습니다.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다