kim366 kim366 - 1 month ago 29
C++ Question

Make Pointer Getter use unique_ptr

sf::RectangleShape* operator()()
{
return &player;

} // RectangleShape Getter


Do I need to free memory after this getter? If yes, how would one do this with
unique_ptr
?

I tried

std::unique_ptr<sf::RectangleShape> operator()()
{
return std::unique_ptr<sf::RectangleShape>(player);

} // RectangleShape Getter


But it says there is no matching function for the parenthesis operator. How else should this be done?

Answer
sf::RectangleShape* operator()()
{
    return &player;

} // RectangleShape Getter

Do I need to free memory after this getter?

All you do is return a pointer to player. Assuming that is a member variable of the struct/class the above member function is a part of, then its lifetime is bound to the lifetime of the object you call that function with.

In particular that means that this is a bad idea:

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?

Assuming sf::RectangleShape has a copy constructor, then you could make a copy of player:

std::unique_ptr<sf::RectangleShape> operator()() {
  return make_unique<sf::RectangleShape>(player);
}

The copy you get that way is "yours", i.e. you can manage is lifetime as you want.

Comments