为什么需要null shared_ptr以及如何使用它?

zha*_*nwu 9 c++ shared-ptr effective-c++ c++11

在Scott Meyers的Effective C++中,第18项使接口易于正确使用且难以正确使用,他提到了null shared_ptr:

std::tr1::shared_ptr<Investment> pInv(static_cast<Investment*>(0), getRidOfInvestment)
Run Code Online (Sandbox Code Playgroud)

和一个时尚分配操作

pInv = ...     //make retVal point to the correct object
Run Code Online (Sandbox Code Playgroud)

在这种情况下,可能需要创建一个null shared_ptr并稍后进行分配?为什么不在有资源(原始指针)时创建shared_ptr?

由于Scott Meyers没有在前面的例子中显示完整的赋值,我认为shared_ptr的assign运算符是重载的,可以这样做:

pInv = new Investment;    // pInv will take charge of the pointer
                          // but meanwhile keep the delete function it already had
Run Code Online (Sandbox Code Playgroud)

但我尝试使用boost的实现它不会这样工作.那么null shared_ptr是什么意思?

我几乎可以肯定我在这里遗漏了一些东西,有人帮我解决了.

PS.更多关于shared_ptr的初始化和赋值

#include <boost/shared_ptr.hpp>

int main(int argc, char *argv[])
{
    boost::shared_ptr<int> ptr1(new int);
    boost::shared_ptr<int> ptr2;
    ptr2.reset(new int);
    boost::shared_ptr<int> ptr3 = new int;

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

这个例子不能由g ++(Ubuntu/Linaro 4.5.2-8ubuntu4)4.5.2和最新的boost 编译:

sptr.cpp: In function ‘int main(int, char**)’:
sptr.cpp:8:39: error: conversion from ‘int*’ to non-scalar type ‘boost::shared_ptr<int>’    requested
Run Code Online (Sandbox Code Playgroud)

bdo*_*lan 19

没有必要使用该hack来获取null(空)shared_ptr.只需使用默认构造函数:

std::shared_ptr<Investment> pInv; // starts null
Run Code Online (Sandbox Code Playgroud)

要指定a的指针shared_ptr,要么在构造时执行:

std::shared_ptr<Investment> pInt(new Investment);
// not allowed due to explicit annotation on constructor:
// std::shared_ptr<Investment> pInt = new Investment;
Run Code Online (Sandbox Code Playgroud)

或者使用.reset()功能:

pInt.reset(new Investment);
Run Code Online (Sandbox Code Playgroud)

该文章的作者可能打算提供自定义删除器(getRidOfInvestment).但是,删除函数在.reset()被调用时被重置,或者在内部指针被改变时被重置.如果您想要自定义删除器,则必须.reset()在创建时将其传递给shared_ptr.

您可能希望使用一种模式来实现更加万无一失的自定义创建功能:

class Investment {
protected:
  Investment();
  // ...
public:
  static shared_ptr<Investment> create();
};

shared_ptr<Investment> Investment::create() {
  return shared_ptr<Investment>(new Investment, getRidOfInvestment);
}
Run Code Online (Sandbox Code Playgroud)

后来:

shared_ptr<Investment> pInv = Investment::create();
Run Code Online (Sandbox Code Playgroud)

这可以确保您始终拥有附加到shared_ptrs创建的s 的正确析构函数Investment.


nau*_*cho 7

原始指针为空的原因相同 - 例如

说你有:

typedef std::tr1::shared_ptr<Investment> InvestmentPtr;
map<key,InvestmentPtr> portfolio;
...
get(mykey) {
  iterator it = portfolio.find(mykey);
  if (it == portfolio.end()) 
    return InvestmentPtr();
  else 
    return it->second;
  }
}
Run Code Online (Sandbox Code Playgroud)

这允许你这样做:

InvestmentPtr p = get(key);
if (p) ...
Run Code Online (Sandbox Code Playgroud)