对于一个 C++ 的 getter 方法,它应该返回一个非平凡类型,但是成员变量却是类或结构体的情况下,最佳实践是什么?
- 按值返回,例如:
MyType MyClass::getMyType() { return mMyType; }
- 通过 const 引用返回:
const MyType& MyClass::getMyType() { return mMyType; }
- 通过地址返回:
MyType* MyClass::getMyType() { return &mMyType; }
其中
class MyType { /* ... */ };
class MyClass
{
private:
MyType mMyType;
}
我特别担心这种方法的以下用法。您能否详细说明如何影响对象的复制,以及如果function()
想要保存它以供进一步使用,悬挂引用和野指针的危险。
MyType* savedPointer;
SomeType function(MyType* pointer) { savedPointer = pointer; };
a. 适用于1和2。
{
MyType t = myClass.getMyType();
function(&t);
}
// is savedPointer still valid here?
b. 适用于1和2。
{
const MyType& t = myClass.getMyType();
function(&t);
}
// is savedPointer still valid here?
c. 适用于1和2。
{
MyType& t = myClass.getMyType();
function(&t);
}
// is savedPointer still valid here?
d. 有效期为3个单位。
{
MyType* t = myClass.getMyType();
function(t);
}
// is savedPointer still valid here?
其中 myClass
是一个类型为 MyClass
的对象。
unique_ptr
,但在这种情况下,你不想返回unique_ptr
的“副本”)。 - James Kanze