简体   繁体   中英

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() ? 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() ?

EDIT: Corrected typo, missing & in int& someMethod()

what is exactly being received in 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()?

That reference may be a memory address, but C++ doesn't dictate how the compiler must implement references. The entire class could exist in a CPU register as well, in which case it has no memory address.

But a copy of m_someDataMember is not made. 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.

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.

See this live example of using a const reference

Edit based on OP changes :

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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