Quick Q: What type to return from a property-style "getter"? -- StackOverflow

Quick A: Reference to const.

c++11 -- Ownership and getters

I'm new to C++ and I have troubles wrapping my head around ownership, specifically with a getter. Here's some example code:

class GameObject {
public:
  Transform *transform();
private:
  Transform _transform;
};

I guess a raw pointer is unsafe to use as someone could access it later when the object doesn't exist anymore?

  1. So I thought about using a unique_ptr for the transform member, since GameObject is the only one that owns the transform. But I can't return that from the getter, can I? But then again, why would I ever use a unique_ptr in the first place instead of adding it as a member like above?
  2. So why not use a shared_ptr? It just seems wrong to me, I don't want to share ownership, GameObject is the owner and others may access it...
  3. So what is it? A reference? I guess shared_ptr seems the wisest choice, since others could safely keep a reference to transform, but what good is that if the enclosing GameObject got destroyed, rendering the transform useless? I'm probably just thinking about ownership the wrong wrong way here but every way seems wrong to me. Thanks for your help.

Add a Comment

Comments are closed.

Comments (0)

There are currently no comments on this entry.