C ++ getter应该返回什么 [英] What should a C++ getter return

查看:72
本文介绍了C ++ getter应该返回什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C ++ getter方法的最佳实践是什么,该方法应该返回非平凡类型,但返回类型为class或struct的成员。

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.


  1. 按值返回,例如: MyType MyClass :: getMyType(){return mMyType; }

  2. 通过const引用返回: const MyType& MyClass :: getMyType(){return mMyType; }

  3. 按地址返回: MyType * MyClass :: getMyType(){return& mMyType; }

  1. Return by value, such as: MyType MyClass::getMyType() { return mMyType; }
  2. Return by const reference: const MyType& MyClass::getMyType() { return mMyType; }
  3. Return by address: MyType* MyClass::getMyType() { return &mMyType; }

其中

class MyType { /* ... */ };

class MyClass
{
  private:
     MyType mMyType;
}

我特别担心此方法的以下用法。您能否详细说明这可能如何影响复制对象,以及如果 function()想要保存它以备将来使用,则有悬挂引用和野生指针的危险。 / p>

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。对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

推荐答案

您可以提供const版本和非const版本:

You can provide both const and non-const versions:

MyType       & MyClass::getMyType()       { return mMyType; }
MyType const & MyClass::getMyType() const { return mMyType; }

我不会提供指针版本,因为这意味着返回值可能为null

I wouldn't provide a pointer version, since that implies that the return value might be the null pointer, which it can never be in this instance.

但是,真正的要点是,您基本上是在给调用方直接访问内部对象的权限。如果这是您的意图,那么您最好将数据成员公开。如果不是,那么您将需要更加努力地隐藏对象。

The real point, however, is that you are basically giving the caller direct access to the internal object. If this is your intent, then you may as well make the data member public. If it isn't, then you will need to work harder to hide the object.

一种选择是保留 MyType const& 访问器,但提供了更多间接方式来修改内部对象( setMyType(…)或更适合您尝试表达的语义的东西包含类的级别)。

One option is to retain the MyType const & accessor, but provide more indirect means to modify the internal object (setMyType(…) or something more tailored to the semantics that you are trying to express at the level of the containing class).

这篇关于C ++ getter应该返回什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆