2008-11-20 66 views
4

我想知道爲什麼shared_ptr沒有隱含的構造函數。它不會是暗示這裏的事實:Getting a boost::shared_ptr for this爲什麼shared_ptr有一個明確的構造函數

(我想出的原因,但認爲這將是一個有趣的問題張貼反正。)

#include <boost/shared_ptr.hpp> 
#include <iostream> 

using namespace boost; 
using namespace std; 

void fun(shared_ptr<int> ptr) { 
    cout << *ptr << endl; 
} 

int main() { 
    int foo = 5; 
    fun(&foo); 
    return 0; 
} 

/* shared_ptr_test.cpp: In function `int main()': 
* shared_ptr_test.cpp:13: conversion from `int*' to non-scalar type ` 
* boost::shared_ptr<int>' requested */ 

回答

8

在這種情況下,shared_ptr會嘗試釋放您的堆棧分配int。你不希望這樣,所以顯式構造函數在那裏讓你思考它。

2

長時間潛行者,和第3年軟式英語學生在這裏, 冒險猜測會阻止你嘗試將一個'自然'指針轉換爲shared_ptr,然後釋放指向的對象,而shared_ptr不知道dealloc。

(另外,引用計數問題等等等等)。

-1
int main() { 

    int foo = 5; 
    fun(&foo); 

    cout << foo << endl; // ops!! 

    return 0; 
} 
+1

我不明白它是如何從根本上`d elete &foo;` – curiousguy 2011-10-07 14:40:40

-3

我認爲沒有理由在此構造函數中有明確的定義。

提到錯誤使用偏移地址運算符(&)的示例沒有意義,因爲在現代C++中沒有地方使用這樣的運算符。除了賦值/比較運算符中的這種慣用代碼爲'this == & other',也許還有一些測試代碼。

+0

@vBx:在提到的示例[1](http://stackoverflow.com/questions/304093/why-shared-ptr-has-an-explicit-constructor/304183#304183)偏移地址運算符(&)已經被用來通過指針傳遞參數給函數。應該改用參考。 – 2011-06-04 10:19:53

6

邏輯的原因是:

  • 調用delete運營商是不是在C++
  • 創造任何擁有智能指針的(shared_什麼,scoped_什麼,...)是隱式真的(延遲)撥打delete運營商
相關問題