简体   繁体   English

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

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

why the result of this code gives the same value of _x and I'm using static instance inside getInstance() it retrieve the same object.为什么此代码的结果给出相同的_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;
}

when I use &A as a type of getInstance() the result is当我将&A用作getInstance()的一种时,结果是

the value of x is: 1 x 的值为:1

the value of x is: 2 x 的值为:2

can anyone explain me why?谁能解释我为什么?

Your AA::getInstance(){ returns a copy of the static instance: static A _instance;您的AA::getInstance(){返回 static 实例的副本static A _instance; . . This copy has a _x equal to the Static A::_x which is initialised to 0 and is not modified.此副本的_x等于 Static A::_x ,它被初始化为 0 且未被修改。

This ultimately means that .print is called on the returned temporary object instead of upon A itself so each time the print function is invoked this temporaty object has its _x incremented and is then destroyed leaving the static A unchanged.这最终意味着.print是在返回的临时文件 object 上调用的,而不是在 A 本身上调用的,因此每次调用打印 function 时,这个临时文件 object 的_x都会增加,然后被销毁,留下 static A 不变。

When you return by reference from A& A::getInstance the .print() acts upon the static A variable twice incrementing it from 0 to 1 then to 2 in the second print.当您从A& A::getInstance通过引用返回时, .print()作用于 static A变量两次,在第二次打印中将其从 0 递增到 1,然后递增到 2。 You would get the same behaviour if you returned by pointer: A* A::getInstance() .如果您通过指针返回,您将获得相同的行为: A* A::getInstance()

I modified your example a bit so you can better see what happens.我稍微修改了您的示例,以便您可以更好地了解会发生什么。 The "problem" (it works exactly as expected) is that if you don't return a reference a copy of A will be returned. “问题”(它完全按预期工作)是如果您不返回引用,将返回 A 的副本。 Run the code and you can see for yourself.运行代码,您可以自己看到。

Note I made the instance getters static so you don't need to create an instance of A first (makes the output more clear).请注意,我创建了实例 getter static,因此您无需先创建 A 的实例(使 output 更清晰)。 And I made the constructor private so you only can use the singleton creation methods.我将构造函数设为私有,因此您只能使用 singleton 创建方法。

Output of the example: 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

And the example itself:以及示例本身:

#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.

相关问题 我如何解决这些错误:必须调用对非静态成员函数的引用,并且在静态成员函数中无效使用成员“mat”? - How do i fix these errors : reference to non-static member function must be called and invalid use of member 'mat' in static member function? 我应该在简单的访问成员函数中使用const返回类型吗? - Should I use const return type in a simple access member function? 我应该在赋值和返回语句中使用static_cast吗?为什么? - Should I use static_cast in assignments and return statements and why? 为什么我不能使用static_cast <int&>将整数引用参数传递给C ++中的函数? - Why can't I use static_cast<int&> to pass an integer reference parameter to a function in C++? 用成员函数启动线程应该传递对象或指针还是引用? - Start a thread with a member function should pass a object or pointer or a reference? 为什么使用函数而不是成员的引用? - Why use a function rather than a reference to member? 为什么我不能使用 static 块来初始化我的 static class 成员? - Why can't I use a static block to initialize my static class member? 对于级联成员函数调用,为什么需要返回引用? 为什么仅此指针还不够? - For cascading member function calls, why do i need to return the reference? Why isn't just the this pointer sufficient? 我应该从静态成员方法返回什么类型的指针 - What type of pointer should I return from static member method 当我从公共成员函数返回引用时,为什么我可以公开私有成员? - Why can I expose private members when I return a reference from a public member function?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM