繁体   English   中英

如果我的 function 使用 static 成员,我为什么要通过引用返回

[英]why should I pass by reference return if my function use static member

为什么此代码的结果给出相同的_x值,而我在getInstance()中使用 static 实例,它检索相同的 object。

  class A{
        public:
        A(){}
        A getInstance();

        void print(){
            _x=_x+1;
            std::cout<<"the value of x is : " <<_x<<std::endl; 
        }

        int _x = 0;

    };



A A::getInstance(){
        static A _instance;
        return _instance;
    }


int main() {

    A a;
    a.getInstance().print(); //the value of x is : 1
    a.getInstance().print(); //the value of x is : 1

    return 0;
}

当我将&A用作getInstance()的一种时,结果是

x 的值为:1

x 的值为:2

谁能解释我为什么?

您的AA::getInstance(){返回 static 实例的副本static A _instance; . 此副本的_x等于 Static A::_x ,它被初始化为 0 且未被修改。

这最终意味着.print是在返回的临时文件 object 上调用的,而不是在 A 本身上调用的,因此每次调用打印 function 时,这个临时文件 object 的_x都会增加,然后被销毁,留下 static A 不变。

当您从A& A::getInstance通过引用返回时, .print()作用于 static A变量两次,在第二次打印中将其从 0 递增到 1,然后递增到 2。 如果您通过指针返回,您将获得相同的行为: A* A::getInstance()

我稍微修改了您的示例,以便您可以更好地了解会发生什么。 “问题”(它完全按预期工作)是如果您不返回引用,将返回 A 的副本。 运行代码,您可以自己看到。

请注意,我创建了实例 getter static,因此您无需先创建 A 的实例(使 output 更清晰)。 我将构造函数设为私有,因此您只能使用 singleton 创建方法。

Output 的例子:

2 times get_Instance
A::A(), _x = 0
A::getInstance(), _instance.x_ = 0
A::A(const A&), _x = 0
the value of x is : 1
A::getInstance(), _instance.x_ = 0
A::A(const A&), _x = 0
the value of x is : 1

2 times get_InstanceRef
A::A(), _x = 0
A::getInstanceRef(), _instance.x_ = 0
the value of x is : 1
A::getInstanceRef(), _instance.x_ = 1
the value of x is : 2

以及示例本身:

#include <iostream>

class A 
{
public:
    static A getInstance();
    static A& getInstanceRef();

    void print() {
        _x = _x + 1;
        std::cout << "the value of x is : " << _x << std::endl;
    }

private:
    A() { std::cout << "A::A(), _x = " << _x << " \n"; }
    A(const A&) { std::cout << "A::A(const A&), _x = " << 0 << "\n" ; }
    int _x = 0;


};

A A::getInstance() 
{
    static A _instance;
    std::cout << "A::getInstance(), _instance.x_ = " << _instance._x << "\n";
    return _instance;
}


A& A::getInstanceRef() 
{
    static A _instance;
    std::cout << "A::getInstanceRef(), _instance.x_ = " << _instance._x << "\n";
    return _instance;
}


int main() 
{
    std::cout << "2 times get_Instance\n";
    auto a1 = A::getInstance();
    a1.print();
    auto a2 = A::getInstance();
    a2.print();

    std::cout << "\n2 times get_InstanceRef\n";
    auto& a3 = A::getInstanceRef();
    a3.print();
    auto& a4 = A::getInstanceRef();
    a4.print();

    return 0;
}

暂无
暂无

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

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