亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

為什么我不能將唯一的PTR推回向量?

為什么我不能將唯一的PTR推回向量?

C++
一只萌萌小番薯 2019-07-05 13:31:25
為什么我不能將唯一的PTR推回向量?這個程序有什么問題?#include <memory>#include <vector>int main(){     std::vector<std::unique_ptr<int>> vec;     int x(1);     std::unique_ptr<int> ptr2x(&x);     vec.push_back(ptr2x); //This tiny command has a vicious error.     return 0;}錯誤:In file included from c:\mingw\bin\../lib/gcc/mingw32/4.5.0/include/c++/mingw32/bits/c++allocator.h:34:0,                 from c:\mingw\bin\../lib/gcc/mingw32/4.5.0/include/c++/bits/allocator.h:48,                 from c:\mingw\bin\../lib/gcc/mingw32/4.5.0/include/c++/memory:64,                 from main.cpp:6:c:\mingw\bin\../lib/gcc/mingw32/4.5.0/include/c++/bits/unique_ptr.h: In member function 'void __gnu_cxx::new_allocator<_Tp>::construct(_Tp*, const _Tp&) [with _Tp = std::unique_ptr<int>, _Tp* = std::unique_ptr<int>*]':c:\mingw\bin\../lib/gcc/mingw32/4.5.0/include/c++/bits/stl_vector.h:745:6:   instantiated from 'void std::vector<_Tp, _Alloc>::push_back(const value_type&) [with _Tp = std::unique_ptr<int>, _Alloc = std::allocator<std::unique_ptr<int> >, value_type = std::unique_ptr<int>]'main.cpp:16:21:   instantiated from herec:\mingw\bin\../lib/gcc/mingw32/4.5.0/include/c++/bits/unique_ptr.h:207:7: error: deleted function 'std::unique_ptr<_Tp, _Tp_Deleter>::unique_ptr(const std::unique_ptr<_Tp, _Tp_Deleter>&) [with _Tp = int, _Tp_Deleter = std::default_delete<int>, std::unique_ptr<_Tp, _Tp_Deleter> = std::unique_ptr<int>]'c:\mingw\bin\../lib/gcc/mingw32/4.5.0/include/c++/ext/new_allocator.h:105:9: error: used hereIn file included from c:\mingw\bin\../lib/gcc/mingw32/4.5.0/include/c++/vector:69:0,                 from main.cpp:7:
查看完整描述

2 回答

?
慕標5832272

TA貢獻1966條經驗 獲得超4個贊

你需要移動unique_ptr:

vec.push_back(std::move(ptr2x));

unique_ptr保證unique_ptr容器擁有持有指針的所有權。這意味著您不能復制unique_ptr(因為那時有兩個unique_ptr我們有所有權),所以你只能移動它。

但是,請注意,您當前使用的unique_ptr是不正確的。不能使用它來管理指向局部變量的指針。局部變量的生存期是自動管理的:局部變量在塊結束時被銷毀(例如,當函數返回時,在本例中)。您需要動態分配對象:

std::unique_ptr<int> ptr(new int(1));


查看完整回答
反對 回復 2019-07-05
?
牛魔王的故事

TA貢獻1830條經驗 獲得超3個贊

STD:UNIQUE_PTR沒有復制構造函數。創建一個實例,然后詢問STD:向量若要在初始化期間復制該實例,請執行以下操作。

error: deleted function 'std::unique_ptr<_Tp, _Tp_Deleter>::uniqu
e_ptr(const std::unique_ptr<_Tp, _Tp_Deleter>&) [with _Tp = int, _Tp_D
eleter = std::default_delete<int>, std::unique_ptr<_Tp, _Tp_Deleter> =
 std::unique_ptr<int>]'

類滿足MoveConstrucable和MoveAssignable的要求,但不滿足CopyConstrucable或CopyAssignable的要求。

以下內容與新的座落打電話。

std::vector< std::unique_ptr< int > > vec;vec.emplace_back( new int( 1984 ) );

看見在標準庫容器中使用UNIQUE_PTR進一步閱讀。


查看完整回答
反對 回復 2019-07-05
  • 2 回答
  • 0 關注
  • 407 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號