返さポインタを介しプライベートフィールドを入力します。ここではいくつかの可能なアプローチは、コメント欄でそれらについての私の疑問に、以下のとおりです。は、私はコンテナクラスを持っている
void initialize(Conatiner& container) {
MyItem item;
container.getItem() = &item; // Wrong, item gets destroyed at the end of the function
container.getItem() = new MyItem();
// This approach is filling my needs so far, but that doesn't necessarily
// mean it's correct.
// In particular, I'm not sure this approach properly removes the original item.
// Here I try to use placement new to reuse the memory pointed to by container.getitem
if (container.getItem()) {
MyItem* pItem = container.getItem();
pItem->~MyItem();
pItem = new (pItem) MyItem();
} // but if the pointer is null, I don't have any memory to reassign!
}
は、ポインタを通じて取り込むフィールドを処理するための慣用的な方法はありますか?私はC++ 11の機能やBoostのような外部ライブラリにアクセスすることはできません。私はContainer
のインターフェースも変更できません。
は、それは危険なことがいくつかのケースでは、それは['のstdの賛成でC++ 11以降廃止されました:: unique_ptr'](http://en.cppreference.com/w/cpp/memory/unique_ptr)、 'std :: auto_ptr'はC++ 17標準から削除されます。 –
パブリック関数を使って変更を許可しようとしているのであれば、なぜそれを非公開にするのでしょうか?とにかく、 '* container.getItem()= MyItem();'はどうでしょうか? –
また、 'getItem'は値*によって格納されたポインタ*を返しますので、左側の' getItem'を使って割り当てを行うことはできません。おそらく、例えば。 '* container.getItem()= MyItem()'はうまくいくはずです。それはスマートポインタの "所有権"モデルをバイパスします。 –