C++Primer第五版 12.1.5節練習
阿新 • • 發佈:2019-01-22
練習12.16:如果你試圖拷貝或賦值unique_ptr,編譯器並不總是能給出易於理解的錯誤資訊。編寫包含這種錯誤的程式,觀察編譯器如何診斷這種錯誤。
答:錯誤程式碼如下
#include <iostream>
#include <memory>
using namespace std;
int main()
{
unique_ptr<int> p(new int(10));
unique_ptr<int> p1(p);//非法拷貝
unique_ptr<int> p2;
p2 = p; //非法賦值
return 0;
}
//編譯器內容
[Error] use of deleted function 'std::unique_ptr<_Tp, _Dp>::unique_ptr(const
std::unique_ptr<_Tp, _Dp>&) [with _Tp = int; _Dp =
std::default_delete<int>]'
練習12.17:下面的unique_ptr宣告中,哪些是合法的,哪些可能導致後續的程式錯誤?解釋每個錯誤的問題在哪裡。
int ix = 1024, *pi = &ix, *pi2 = new int(2048);
typedef unique_ptr<int> IntP;
(a) IntP p0(ix); //錯誤 型別不一致,無法賦值
(b) IntP p1(pi); //正確 p1指向pi2
(c) IntP p2(pi2); //正確 p2指向pi2
(d) IntP p3(&ix); //正確 p3指向ix的地址
(e) IntP p4(new int(2048)); //正確
(f) IntP p5(p2.get()); //正確
練習12.18:shared_ptr為什麼沒有release成員?
網上參考答案:release使智慧指標和 指標分離了, 使用之後需要單獨delete釋放指標,如果只是當前shared_ptr, 就不叫”release”了