c – 为什么需要一个空的shared_ptr,如何使用?
在Scott Meyers的Effective C中,项目18使界面易于正确使用,难以正确使用,他提到了null shared_ptr:
std::tr1::shared_ptr<Investment> pInv(static_cast<Investment*>(0),getRidOfInvestment) 和时尚派对操作 pInv = ... //make retVal point to the correct object 在这种情况下,可能需要创建一个空的shared_ptr并稍后执行分配?为什么不用创建shared_ptr,只要你有资源(raw指针)? 由于Scott Meyers在前面的例子中没有显示完整的作业,我认为shared_ptr的赋值操作符是重载的,可以这么做: pInv = new Investment; // pInv will take charge of the pointer // but meanwhile keep the delete function it already had 但是我尝试使用boost的实现,它不会这样工作.那么有什么意义上有空的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; } 这个例子无法由g(Ubuntu / Linaro 4.5.2-8ubuntu4)4.5.2和最新的提升编译: 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 解决方法
没有必要使用这个hack来获取一个null(空)shared_ptr.只需使用默认构造函数:
std::shared_ptr<Investment> pInv; // starts null 要指定一个指向shared_ptr的指针,可以在构建时执行: std::shared_ptr<Investment> pInt(new Investment); // not allowed due to explicit annotation on constructor: // std::shared_ptr<Investment> pInt = new Investment; 或使用.reset()函数: pInt.reset(new Investment); 该文章的作者有可能希望提供一个自定义的删除(getRidOfInvestment).但是,当调用.reset()时,或者当内部指针被改变时,删除功能被重置.如果你想要一个自定义的删除器,你必须在创建shared_ptr时将其传递给.reset(). 您可能想要使用这种更加愚蠢的模式是自定义创建功能: class Investment { protected: Investment(); // ... public: static shared_ptr<Investment> create(); }; shared_ptr<Investment> Investment::create() { return shared_ptr<Investment>(new Investment,getRidOfInvestment); } 后来: shared_ptr<Investment> pInv = Investment::create(); 这将确保您始终拥有从投资创建的shared_ptrs附加的正确析构函数. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |