提供非const引用getter是有意义的 [英] Does it make sense to provide non-const reference getter

查看:191
本文介绍了提供非const引用getter是有意义的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有时我需要暴露一些类成员。例如,在下面的示例类Mechanic 可能需要直接访问 Engine 组件。我已经读了很多次,所有字段应该被访问器(访问器)方法访问,因为几个原因。但是提供非const引用getter时有什么优势:

Sometimes I need to expose some of the class members. For example in the following example class Mechanic may need direct access to Engine component. I have read many times that all fields should be accessed by mutator (accessor) methods because of several reasons. But is there any advantage when providing non-const reference getter:

class Car
{
    public:
        Engine & engine()
        {
           return m_engine;
        }

        //as a consequence you will also need to provide const version
        const Engine & engine() const
        {
           return m_engine;
        }

    private:
       Engine m_engine;
}

b $ b

class Car
{
    public:
        Engine engine;
}

您也可以替换 public protected ,如果你不喜欢这个例子。在现实生活中,当涉及到 System.in System.out 时,你在Java中有类似的东西。看起来,为了完全符合某些人的说法,你需要执行 System.getInstance()。getOut()。println(hello world)。在这种情况下,除了很多官僚代码,我看不到任何好处。

You can also replace public with protected if you don't like this example. In real life you have something simillar in Java when it comes to System.in or System.out. It looks like, to be fully compliant on what some people say, you would need to perform calls like System.getInstance().getOut().println("hello world"). I don't see any benefit except a lot of bureaucratic code in such cases.

推荐答案

吸气剂。它使您的软件的集成更容易(例如,当您想将界面翻译成另一种语言并绑定ABI)。

I have found reasonable point to provide such getter. It makes integration of your software easier (for example, when you want to translate interface into another language and bind ABIs).

这篇关于提供非const引用getter是有意义的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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