简体   繁体   中英

C++ reference copying and assignment

I have few questions regarding below code

#include <iostream>

using namespace std;

class A
{
public:
 A &  add(A & b);
};

A &  A::add(A & z)
{
    A * a = new A();
    A & b = *a;
    cout << "Inside add, address of a: " << &a << endl;
    cout << "Inside add, address of b: " << &b << endl;
    cout << "Inside add, address of z: " << &z << endl;
    A aa;
    cout << "Inside, add, address of aa: " << &aa << endl;
    return aa;
}


int main()
{

    A *a = new A();
    cout << "Original a: " << a << endl;
    A & b = a->add(*a);
    cout << "b: " << &b <<  endl;
    return 0;
}

Q1. Inside main, line 3, a->add(*a) , the same object pointed by pointer *a is passed. But inside the function A::add(A &) , when i try to achieve the same effect via A &b = *a , i get a different object. Why is this so?

Q2. Inside A::add(A &) , i return a non const reference to a local object aa and main gets the same memory address as the local reference. So this has the effect of extending the lifetime of local reference, beyond its scope.

Q3. Inside A::add(A &) , i dereference *a multiple times, first via A &b = *a and then by return *a . In both cases, the memory address is always the same. How is this happening? You can check the output of &b inside A::add(A &) and the result of A &b = a->add(*a)

UPDATE:

  1. The issue related to Q1 was that i was doing cout << &a , when i should have been doing cout << a

  2. To eliminate return value optimization, i compiled with -fno-elide-constructors. I am using g++.

A1: You created a new *a with A* a = new A() The a in main is different than the a in A::add . The a in main is referenced by the variable z

A2: No, you created a on the heap, so it is going to last until you call delete on that variable

A3: A dereference does not change the memory location that is stored in the pointer, it just gets the value stored in that location. A reference is more like an alias. So &b is like saying &(*a)

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