Question

I'm storing an object internally(private) as a QSharedPointer(so it will delete it). For the getter should I return a reference a raw pointer or a QSharedPointer?

Also I'm not sure what http://qt-project.org/wiki/SharedPointersAndQmlOwnership means. Could someone summarise it for me?

No correct solution

OTHER TIPS

Ultimately, you are defining the semantics of the getter. It's up to you to specify the lifetime of any objects returned by it.

Specifically, if whatever the getter returns is expected to outlive the object whose member the getter is, then you must either:

  • return a shared pointer, or

  • return a copy.

Your internally stored object could be implicitly shared (say using QSharedData and QSharedDataPointer (not same as QSharedPointer!), so that the copy could be cheap to make if not subject to further modification.

If whatever the getter returns only needs to be alive and valid as long as the object whose member the getter is, then you can also offer the following options:

  • return a reference,

  • return a const reference,

  • return a plain pointer (non-smart).

Nominally, the values returned by getters that return references and plain pointers are presumed to be useless when the object whose member the getter is, dies. Only if the ownership to a heap-allocated object is passed to the caller, by returning a pointer, can the presumption be broken by explicitly documenting the "getter" as doing so.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top