[英]error in moving std::unique_ptr
我嘗試運行以下代碼以將unique_ptr的值從第一個向量移動到副本構造函數中的另一個向量:
class Text
{
struct paragraph
{
int index;
string text;
};
vector<unique_ptr<paragraph>> paragraphs;
public:
Text()
{
paragraphs.push_back(unique_ptr<paragraph>(new paragraph));
}
Text(const Text & t)
{
for(int i = 0; i < (int)t.paragraphs.size(); i++)
{
paragraphs.push_back(move(t.paragraphs[i]));
}
}
};
我得到了這個錯誤:
1>c:\program files\microsoft visual studio 10.0\vc\include\xmemory(208): error C2248: 'std::unique_ptr<_Ty>::unique_ptr' : cannot access private member declared in class 'std::unique_ptr<_Ty>'
1> with
1> [
1> _Ty=Text::paragraph
1> ]
// Etc.
您的代碼有幾處錯誤。
首先,您不能從const&
移開,這也適用於const&
成員。 運動具有破壞性; 您只能從&&
移開。 你的復制構造器應該復制 ; 如果您不想要復制構造函數,則= delete
它或編譯器允許的任何形式。
其次,假設您為適當的move構造函數進行了Test &&
,則不應該這樣移動每個元素。 而是將向量移到新的向量中,如下所示:
Text(Text && t) : paragraphs(std::move(t.paragraphs)) {}
第三,您只應在假設您選擇的編譯器不支持自動生成的move構造函數(即Visual Studio)的情況下編寫此函數。 如果它支持它,那么您根本不應該編寫一個 。 讓編譯器完成任務。
Text(const Text & t)
{
for(int i = 0; i < (int)t.paragraphs.size(); i++)
{
paragraphs.push_back(move(t.paragraphs[i]));
}
}
在此構造函數中, t
為const,因此t.paragraphs[i]
給出了對unique_ptr
的const左值引用。
move(t.paragraphs[i])
將其轉換為const rvalue引用,但仍為const。 unique_ptr
move構造函數需要一個非常量右值引用,因此不可行,因此刪除的副本構造函數是最佳匹配。 您不應該嘗試在副本構造函數中移動t
的內容,這就是move構造函數的作用。
您還應該說std::move
不只是move
,以防止ADL找到錯誤的動作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.