此代碼編譯成功。錯誤:這裏聲明unique_ptr(const unique_ptr&)= delete;
#include<iostream>
#include<memory>
using namespace std;
class A{
public:
unique_ptr<A> myval;
A(){ cout<<"Constrcutor of A is called"<<endl; }
~A(){cout<<"Destructor of A is called"<<endl;}
unique_ptr<A> getsomething()
{
unique_ptr<A> myval;
myval.reset(new A);
return myval;
}
};
但是當我評論本地unique_ptr<A> myval;
編譯器會拋出錯誤。
shared_test.cpp: In member function ‘std::unique_ptr<A> A::getsomething()’:
shared_test.cpp:12:10: error: use of deleted function ‘std::unique_ptr<_Tp, _Dp>::unique_ptr(const std::unique_ptr<_Tp, _Dp>&) [with _Tp = A; _Dp = std::default_delete<A>]’
return myval;
^
In file included from /usr/include/c++/4.8/memory:81:0,
from shared_test.cpp:2:
/usr/include/c++/4.8/bits/unique_ptr.h:273:7: error: declared here
unique_ptr(const unique_ptr&) = delete;
^
我無法理解這個錯誤的含義。它是什麼?
你明白爲什麼原始代碼會編譯嗎?因爲這也是一個有趣的問題,如果你不這樣做,這個答案可能會很長。 – juanchopanza