![](/img/trans.png)
[英]Why does a explicit constructor expecting std::shared_ptr accept a nullptr?
[英]Why shared_ptr has an explicit constructor
我想知道為什么shared_ptr
沒有隱式構造函數。 它沒有被提及的事實: 為此得到一個boost :: 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 */
在這種情況下,shared_ptr將嘗試釋放分配給int的堆棧。 您不希望這樣,因此可以使用顯式構造函數來考慮它。
邏輯原因是:
delete
運算符在C ++中不是隱式的 shared_
任意, scoped_
任意...) 實際上是(延遲)調用delete
運算符 很久以前潛伏了,這里有3年級的軟件工程專業學生,Hapazar猜測可能是這樣,這可以阻止您嘗試將“自然”指針轉換為shared_ptr,然后取消分配有針對性的對象,而無需shared_ptr知道取消分配。
(此外,引用計數問題等等)。
int main() {
int foo = 5;
fun(&foo);
cout << foo << endl; // ops!!
return 0;
}
我認為沒有理由在此構造函數中具有顯式的名稱。
所提到的示例不正確地使用了偏移地址運算符(&),因為在現代C ++中沒有使用此類運算符的地方。 除了賦值/比較運算符中的慣用代碼(如“ this ==&other”)和一些測試代碼外。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.