[英]Usage of std::swap() inside move assignment should cause endless recursion (and causes), but it is an example from Stroustrup's book
我試圖深入了解我應該如何編寫復制和移動構造函數和賦值運算符。
在 Bjarne Stroustrup 的“The C++ Programming Language - 2013”中,我看到了以下移動構造函數和移動賦值的示例:
template<class T, class A>
vector_base<T,A>::vector_base(vector_base&& a)
: alloc{a.alloc},
elem{a.elem},
space{a.space},
last{a.space}
{
a.elem = a.space = a.last = nullptr; // no longer owns any memory
}
template<class T, class A>
vector_base<T,A>::& vector_base<T,A>::operator=(vector_base&& a)
{
swap(∗this,a);
return *this;
}
(旁注:書中似乎有一個錯字::: ::&
應該只是&
,對嗎? )
我懷疑它應該導致無限遞歸,因為std::swap()
調用移動賦值運算符:
template<typename T>
void swap(T& lhs, T& rhs)
{
auto temp(lhs);
lhs = std::move(rhs);
rhs = std::move(temp);
}
我已經檢查過了,這是一個非常簡單的程序:
#include <iostream>
using namespace std;
class TestA {
int x;
public:
TestA(int x = 0) : x(x) {
cout << "TestA value ctor " << x << "\n";
}
~TestA() {
cout << "TestA dtor " << x << "\n";
}
TestA(const TestA &a) : x(a.x) {
cout << "TestA copy ctor " << x << "\n";
}
TestA(TestA &&a) : x(a.x) {
cout << "TestA move ctor " << x << "\n";
}
TestA operator=(const TestA &a) {
x = a.getX();
cout << "TestA copy assignment " << x << " = " << a.getX() << "\n";
return *this;
}
TestA &operator=(TestA &&a) {
cout << "TestA move assignment " << x << " = " << a.getX() << "\n";
swap(*this, a);
return *this;
}
int getX() const {
return this->x;
}
};
int main(void) {
TestA a{0};
TestA b{1};
{
TestA c{2};
a = move(c);
}
}
這產生以下輸出,所以我對無限遞歸是正確的:
TestA value ctor 0
TestA value ctor 1
TestA value ctor 2
TestA move assignment 0 = 2
TestA move ctor 0
TestA move assignment 0 = 2
TestA move ctor 0
TestA move assignment 0 = 2
TestA move ctor 0
...
...
我錯過了什么嗎? 如何在移動分配中使用swap()
?
您缺少的是 Stroustroup 在與類相同的命名空間中提供了一個自由函數swap(TestA&, TestA&)
。
此外,他沒有將其稱為std::swap
(您的代碼也沒有),而是使用不合格的 id 並通過using ::std::swap;
將std::swap
注入到命名空間中using ::std::swap;
.
這意味着不使用標准提供的通用版本。
至少它應該是這樣。 似乎真的缺少獨立的swap()
。 哎喲。
你沒有遺漏任何東西,接受的答案是錯誤的。 Stroustrup 的書簡直糟透了。 第 13 章中的任何地方都沒有獨立的swap()
; 強烈暗示這個swap()
是std::swap()
(就像copy()
是std::copy()
等)。 這只是一個錯誤。 歡迎使用 C++。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.