简体   繁体   English

C ++:通过成员函数中的引用返回成员变量

[英]C++: Returning a member variable by reference in member function

Suppose I have the following structure: 假设我具有以下结构:

class HeavyClass {

    public:
        static inline HeavyClass const &get() { // note the &
            return h_;
        }
    private:
        static HeavyClass h_;
};

HeavyClass HeavyClass::h_();

int main() {
    HeavyClass foo = HeavyClass::get(); // critical line
    return 0;
}

My question is, will this actually do what I want at the critical line? 我的问题是,这实际上会满足我在关键线上的要求吗? That is, will foo be a copy of h_, or actually h_ as if it's passed by reference? 也就是说,foo是h_的副本,还是实际上是通过引用传递的h_?

Many thanks! 非常感谢!

I would think you need something like: 我认为您需要类似的东西:

const HeavyClass& foo = HeavyClass::get();

If you want foo to be h_ . 如果您希望fooh_

You are making a copy. 您正在复制。

The function get does indeed return a reference, but you are assigning it by-value: 函数get确实确实返回了引用,但是您正在按值分配它:

HeavyClass foo = HeavyClass::get(); // critical line

On the critical line here, the critical part is the definition of foo . 在关键点上,关键部分foo的定义。 foo isn't a reference-to- HeavyClass -- it's a HeavyClass itself. foo不是对HeavyClass的引用-它本身就是HeavyClass Therefore, foo cannot be a reference to anything. 因此, foo 不能引用任何东西。

There is no magic in C++, only logic. C ++中没有魔术,只有逻辑。 Well, OK, maybe there is magic, but none of it is hidden. 好吧,也许有魔术,但是没有一个是隐藏的。 It;'s all in plain sight. 一切都在眼前。 Here you declared a HeavyClass , not a reference-to- HeavyClass , so it doesn't magically become a reference. 在这里,您宣布HeavyClass ,而不是一个参考TO- HeavyClass ,所以它不会奇迹般地变成了参考。

If you want a reference, declare foo like this: 如果要引用,请像这样声明foo:

const HeavyClass& foo = HeavyClass::get()

By the way, it looks like you're trying to build a Singleton. 顺便说一句,您似乎正在尝试构建Singleton。 Please, at least research and be cognizant of all the arguments why Singletons are considered to be generally bad before you continue. 请至少进行研究并充分理解为什么在继续之前,单身人士通常被认为是不好的所有观点。

The value of the right-hand side is not relevant for determining the type of the variable, which you have declared to be of type HeavyClass . 右侧的值与确定已声明为HeavyClass类型的变量的类型HeavyClass So a new object of that type is instantiated and initialized with the value on the right. 因此,将使用右侧的值实例化并初始化该类型的新对象。 The fact the right-hand side is an lvalue doesn't matter (it will be subjected to lvalue-to-rvalue conversion). 右侧是左值这一事实无关紧要(它将接受左值到右值的转换)。

Whether a function's return type is a reference or not doesn't change the value of the function call, only the value category . 无论是函数的返回类型是引用还是不不会改变函数调用的价值 ,只有价值范畴

Note that this is exactly the same with auto : If you had said auto x = HeavyClass::get(); 请注意,这与auto完全相同:如果您说过auto x = HeavyClass::get(); , it'd be the same, for the same reason ( auto deduces type, not value category). ,出于相同的原因( auto推导类型,而不是值类别),结果会相同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM