簡體   English   中英

這個unique_ptr的初始化有什么問題?

[英]What's wrong with this initialization of unique_ptr?

有人可以告訴我,unique_ptr的以下初始化有什么問題?

int main()
{
  unique_ptr<int> py(nullptr);
  py = new int;
  ....
}

g ++ -O2 xxx.cc -lm -o xxx -std = c ++ 11說:

error: no match for ‘operator=’ (operand types are    ‘std::unique_ptr<int>’ and ‘int*’)
   py = new int;
      ^

unique_ptr<int> px(new int);

工作得很好。

初始化在兩段代碼中都很好, unique_ptr具有nullptr和裸指針的構造函數

第一個片段中失敗的是賦值,這是因為unique_ptr沒有一個operator= overload,它接受一個裸指針作為它的右側。 它確實接受另一個unique_ptr ,所以你可以這樣做:

py = unique_ptr<int>{new int};
py = std::make_unique<int>(); // Since c++14

或者你可以看看reset ,它也接受一個裸指針並具有或多或少相同的含義:

py.reset(new int);

關於

unique_ptr的以下初始化有什么問題?

這不是初始化有問題,而是以下任務。

這就是錯誤消息中的插入符號(向上箭頭)指向的位置:在賦值時。 強提示:使用reset成員函數,或創建unique_ptr實例。


關於

 unique_ptr<int> px(new int); 

工作正常。

它是指向unique_ptr的原始指針的賦值,這是有問題的,而不是初始化。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM