sf::RectangleShape* operator()()
{
return &player;
} // RectangleShape Getter
Do I need to free memory after this getter?
あなたが行うすべてはplayer
へのポインタを返すです。それがstruct/classのメンバ変数であり、上記のメンバ関数がその一部であると仮定すると、その寿命は、その関数を呼び出したオブジェクトの存続期間に縛られます。これは悪い考えであることを意味し、特に
:sf::RectangleShape
を想定し
struct Foo {
sf::RectangleShape player;
// ...
// insert your operator here
};
sf::RectangleShape * some_function(void) {
Foo f;
return f(); // UB, returning pointer to object with automatic memory whose lifetime has ended
}
[..] how would one do this with unique_ptr?
は、コピーコンストラクタを持っている、あなたはplayer
のコピーを作ることができる:
std::unique_ptr<sf::RectangleShape> operator()() {
return make_unique<sf::RectangleShape>(player);
}
コピーあなたはその方法を "あなたのもの"にします。つまり、あなたが望むように生涯を管理することができます。
ユニークなポインタは、 'make_unique'から返されるか、そうでなければ' new'式の値から構築されなければなりません。 –
'プレーヤー 'とは何ですか? – Galik
最初の例でアドレスを取っているので、 'player'はポインタではないようです。 – krzaq