简体   繁体   English

当我们通过引用使用方法作为参数时,实际上发生了什么?

[英]What's really happening when we use a method as a parameter by reference?

Suppose this: 假设这:

class A
{
    public:
        A(int x) : m_someDataMember(x) {}
        ~A() {}
        int& someMethod(){ return m_someDataMember; }

    private:
        int m_someDataMember;
};

class B
{
    public:
    B(){}
    ~B(){}
    void anotherMethod(int& someInt){ /*...*/}
};

Now in main, 现在主要

int main(/*..*/)
{
    A a(5);
    B b;
    b.anotherMethod(a.someMethod());
}

My question being, what is exactly being received in anotherMethod() ? 我的问题是, anotherMethod()到底收到了什么? Is it the memory address itself of m_someDataMember from object a, or the memory address of a copy of m_someDataMemeber returned by a.someMethod() ? 难道是内存地址本身的m_someDataMember从对象,或副本的内存地址m_someDataMemeber由归国a.someMethod()

EDIT: Corrected typo, missing & in int& someMethod() 编辑:纠正错字,缺少& int& someMethod()

what is exactly being received in anotherMethod()? 在anotherMethod()中到底收到了什么?

A reference to that same variable is received. 收到对该相同变量的 引用

Is it the memory address itself of m_someDataMember from object a or the memory address of a copy of m_someDataMemeber returned by a.someMethod()? 它是对象a中m_someDataMember的内存地址本身,还是a.someMethod()返回的m_someDataMemeber副本的内存地址?

That reference may be a memory address, but C++ doesn't dictate how the compiler must implement references. 该引用可能是一个内存地址,但是C ++并未规定编译器必须如何实现引用。 The entire class could exist in a CPU register as well, in which case it has no memory address. 整个类也可以存在于CPU寄存器中,在这种情况下,它没有内存地址。

But a copy of m_someDataMember is not made. 但是不会创建m_someDataMember的副本。 It refers to the same variable. 它引用相同的变量。

It will be a compiler error as you are trying to bind a non const reference to a temporary object. 当您尝试将非const引用绑定到临时对象时,这将是编译器错误。

See this live example 看到这个现场的例子

You can fix this by either having someMethod() return a reference which you might not want to do or you can take a const reference. 您可以通过使someMethod()返回您可能不想执行的引用来解决此问题,也可以采用const引用。

See this live example of using a const reference 请参阅此使用const引用的实时示例

Edit based on OP changes : 根据OP更改进行编辑

If you have a function that returns a reference and you call that function in the parameter list of another function then that function will be referencing whatever variable the first function returned. 如果您有一个返回引用的函数,并且在另一个函数的参数列表中调用了该函数,则该函数将引用第一个函数返回的任何变量。 No copy will be made in this instance. 在这种情况下,不会进行任何复制。

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

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