What is the best practice for a C++ getter method which is supposed to return a non trivial type, but a member which is of type class, or struct.
- Return by value, such as:
MyType MyClass::getMyType() { return mMyType; }
- Return by const reference:
const MyType& MyClass::getMyType() { return mMyType; }
- Return by address:
MyType* MyClass::getMyType() { return &mMyType; }
where
class MyType { /* ... */ };
class MyClass
{
private:
MyType mMyType;
}
I specifically worry about the following usages of this method. Can you please elaborate in details how this might affect copying the object, and the danger of dangling references and wild gone pointers if function()
wants to save it for further usage.
MyType* savedPointer;
SomeType function(MyType* pointer) { savedPointer = pointer; };
a. valid for 1. and 2.
{
MyType t = myClass.getMyType();
function(&t);
}
// is savedPointer still valid here?
b. valid for 1. and 2.
{
const MyType& t = myClass.getMyType();
function(&t);
}
// is savedPointer still valid here?
c. valid for 1. and 2.
{
MyType& t = myClass.getMyType();
function(&t);
}
// is savedPointer still valid here?
d. valid for 3.
{
MyType* t = myClass.getMyType();
function(t);
}
// is savedPointer still valid here?
where myClass
is an object of type MyClass
.