boost :: shared_ptrは本当に気になります。確かに、私はこのようなことの有用性を理解していますが、私はshared_ptr<A>
をとA*
と使用したいと考えています。 HelpfulContainerは、オブジェクトへのポインタを保持したい他の人のことを考えていなかった作成誰以下のコードC++:オブジェクトへの共有ポインタではなく、共有オブジェクトを作成する
class A
{
public:
A() {}
A(int x) {mX = x;}
virtual void setX(int x) {mX = x;}
virtual int getX() const {return mX;}
private:
int mX;
};
class HelpfulContainer
{
public:
//Don't worry, I'll manager the memory from here.
void eventHorizon(A*& a)
{
cout << "It's too late to save it now!" << endl;
delete a;
a = NULL;
}
};
int main()
{
HelpfulContainer helpfulContainer;
A* a1 = new A(1);
A* a2 = new A(*a1);
cout << "*a1 = " << *a1 << endl;
cout << "*a2 = " << *a2 << endl;
a2->setX(2);
cout << "*a1 = " << *a1 << endl;
cout << "*a2 = " << *a2 << endl;
cout << "Demonstrated here a2 is not connected to a1." << endl;
//hey, I wonder what this event horizon function is.
helpfulContainer.eventHorizon(a1);
cout << "*a1 = " << *a1 << endl;//Bad things happen when running this line.
}
を考えてみましょう。 HelpfulClassにboost :: shared_ptrオブジェクトを与えることはできません。しかし、我々は何ができる一つのことは、Aである自分自身SharedAを作成するためにpimlpイディオムを使用している:
class SharedA : public A
{
public:
SharedA(A* a) : mImpl(a){}
virtual void setX(int x) {mImpl->setX(x);}
virtual int getX() const {return mImpl->getX();}
private:
boost::shared_ptr<A> mImpl;
};
そして主な機能は次のようなものに見えることができます:私、そう
int main()
{
HelpfulContainer helpfulContainer;
A* sa1 = new SharedA(new A(1));
A* sa2 = new SharedA(sa1);
cout << "*sa1 = " << *sa1 << endl;
cout << "*sa2 = " << *sa2 << endl;
sa2->setX(2);
cout << "*sa1 = " << *sa1 << endl;
cout << "*sa2 = " << *sa2 << endl;
cout << "this demonstrates that sa2 is a shared version of sa1" << endl;
helpfulContainer.eventHorizon(sa1);
sa2->setX(3);
//cout << "*sa1 = " << *sa1 << endl;//Bad things would happen here
cout << "*sa2 = " << *sa2 << endl;
//but this line indicates that the originally created A is still safe and intact.
//only when we call sa2 goes out of scope will the A be deleted.
}
を質問はこれです:上記のパターンは良いパターンですか、私はまだ検討していないものがありますか?私の現在のプロジェクトは、上記のようなHelpfulContainer
クラスを継承しています。それは必要なポインタを削除していますが、HelpfulContainerにはまだデータ構造が必要です。
更新:このquestionは、後に続く質問です。
HelpfulContainerがポインタの所有権を取得したい場合は、正しいセマンティクスを使用する必要があります。インターフェース 'eventHorizon'は、何が起こっているのかを説明していないので、所有名が転送されていることを示すパラメータ(例えば、std :: auto_ptrまたはその新しい置換std :: unique_ptr)が記述されています。これらの両方は、HelpfullContainerオブジェクトがオブジェクトの所有権を取得しているため、呼び出し後も有効ではなくなることを示します。したがって、C++コードでは、言語の意味を理解していない人がひどく書くことができるという点を証明します。 –