【问题标题】:Why shared_ptr has an explicit constructor为什么 shared_ptr 有一个显式的构造函数
【发布时间】:2010-09-23 04:14:42
【问题描述】:

我想知道为什么shared_ptr 没有隐式构造函数。事实并非如此:Getting a boost::shared_ptr for this

(我找到了原因,但认为无论如何发布这个问题会很有趣。)

#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 */

【问题讨论】:

    标签: c++ boost refcounting


    【解决方案1】:

    在这种情况下,shared_ptr 将尝试释放您分配的 int 堆栈。你不会想要这样,所以显式构造函数可以让你考虑它。

    【讨论】:

      【解决方案2】:

      合乎逻辑的原因是:

      • 调用 delete 运算符在 C++ 中并不隐含
      • 创建任何拥有的智能指针shared_whatever、scoped_whatever、...)实际上是对 delete 运算符的(延迟)调用

      【讨论】:

        【解决方案3】:

        潜伏已久,这里是软工程三年级的学生, 随意的猜测是,阻止您尝试将“自然”指针转换为 shared_ptr,然后释放指向的对象,而 shared_ptr 不知道释放。

        (另外,引用计数问题等等)。

        【讨论】:

          【解决方案4】:
          int main() {
          
              int foo = 5;
              fun(&foo);
          
              cout << foo << endl; // ops!!
          
              return 0;
          }
          

          【讨论】:

          • 我看不出它与delete &amp;foo;有什么根本不同
          【解决方案5】:

          我认为没有理由在这个构造函数中显式。

          提到的错误使用偏移地址运算符 (&) 的示例毫无意义,因为在现代 C++ 中没有使用此类运算符的地方。除了赋值/比较运算符中的惯用代码,例如 'this == &other' 和一些测试代码。

          【讨论】:

          • @vBx:在提到的示例中,1 偏移地址运算符 (&) 已用于通过指针将参数传递给函数。应该使用参考。
          • operator&amp; 给出了地址,而不是左值的“偏移量”(无论这意味着什么)。
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-07-29
          • 1970-01-01
          • 1970-01-01
          • 2020-05-31
          相关资源
          最近更新 更多