在C ++中在函数名前使用和号的启示? [英] Implications of using an ampersand before a function name in C++?

查看:145
本文介绍了在C ++中在函数名前使用和号的启示?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如:

  inline string& GetLabel(){
return m_Label;
};

其中m_Label是一个私有类成员变量。



我认为我的理解,这个函数将返回一个对变量m_Label的引用。在我的程序中使用这将是什么的意义,它会更好只是返回的值,而不是参考?谢谢!

解决方案

它返回对私人成员的引用。



在许多情况下,这是可取的,但是应该注意。



IMO通常不是一个好的主意,返回一个内部对象的副本,类型,出于整体性能原因。是的,我知道,提前优化不好,但这不是真正的优化,它只是一个良好的性能实践,允许调用者确定性能的影响;如果它想要一个副本,它只能不声明它分配给它作为参考的变量。



这里有两个一般的经验规则: p>

1)如果你不希望调用者直接修改私有对象,可以将返回值声明为const引用:

  inline const string& GetLabel()const {return m_Label; } 

2)调用者不应该存储从类方法返回的引用,



如果由于某种原因需要调用方来存储对内部对象的引用,请改用智能指针。


Given the example:

inline string &GetLabel( ) {
        return m_Label;
};

Where m_Label is a private class member variable.

The way I think I understand it, this function will return a reference to the variable m_Label. What would be the implications of using this throughout my program and would it be a better to just return the value, instead of the reference? Thank you!

解决方案

It returns a reference to the private member.

There are many cases where this is desirable, but some care should be taken.

IMO it's generally not a good idea to return a copy of an internal object that is not an integral type, for overall performance reasons. Yes I know, premature optimization is not good, but this is not really optimization, it's just a good performance practice that allows the caller to determine the performance implications; if it wants a copy, it can just not declare the variable that it's assigning it to as a reference.

There are 2 general rules of thumb I use here:

1) If you don't want the caller to be able to modify the private object directly, declare the return value as a const reference:

inline const string& GetLabel() const{ return m_Label; }

2) A caller should never store the reference returned from a class method, it should only be used locally where the parent object is guaranteed to be in scope.

If for some reason you need callers to be able to store a reference to your internal objects, use smart pointers instead.

这篇关于在C ++中在函数名前使用和号的启示?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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