为什么shared_ptr有一个显式的构造函数

cdl*_*ary 4 c++ boost refcounting

我想知道为什么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 */
Run Code Online (Sandbox Code Playgroud)

cad*_*bra 8

在这种情况下,shared_ptr将尝试释放已分配int的堆栈.你不会想要那个,所以显式构造函数会让你思考它.


cur*_*guy 5

合乎逻辑的原因是:

  • 调用delete运算符不是C++中隐含的
  • 创建任何拥有的智能指针(shared_无论如何,scoped_......)实际上是对delete操作员的(延迟)调用