ScottMeyersのEffectiveC++の項目18で、インターフェイスを正しく使いやすく、正しく使いにくいようにする、と彼はnullshared_ptrについて言及しました。
std::tr1::shared_ptr<Investment> pInv(static_cast<Investment*>(0), getRidOfInvestment)
と流行の割り当て操作
pInv = ... //make retVal point to the correct object
その場合、nullのshared_ptrを作成し、後で割り当てを行う必要がありますか?リソース(生のポインター)があるときはいつでも、shared_ptrを作成しないのはなぜですか?
前の例ではScottMeyersが完全な代入を示していなかったため、shared_ptrの代入演算子がオーバーロードされてこれを実行できると思いました。
pInv = new Investment; // pInv will take charge of the pointer
// but meanwhile keep the delete function it already had
しかし、私はブーストの実装で試しましたが、このようには機能しません。では、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;
}
この例は、 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