开发者

About returning references to objects

No, this isn't about the mistake everyone makes of passing locals. I'm just trying to understanding returning a reference to an object you pass in (I'm reading through primer).

So if I have a function like this:

const foo & foo::function2(const foo &开发者_开发百科; val) const
{
    using namespace std;
    return *this;
}

and then I'm in main doing this:

foo object1;
object1.someproperty = 7;

foo object2 = object1.function2(object1);
object2.someproperty = 5;

cout << &object1 << endl;
cout << &object2 << endl;

When I return by reference, shouldn't object2 have the same address (and properties) as object1? Shouldn't changing "someproperty" in one object alter the value in the other? Or, does returning a reference to an object simply copy over the values into the new object?

It seems like the same thing is going on as if I just said that I was going to return a foo object instead of a reference to one.


foo object2 = object1.function2(object1);

function2() returns a reference to object1; the foo copy constructor is then invoked to copy object1 into object2, because object2 is declared as a foo object.

If you declared object2 as a const reference instead:

const foo& object2 = object1.function2(object1);

then object2 would be a reference to object1.


You hit the automatic copy constructor when you assigned to object2. Effectively what happened was:

foo object2(object1.function2(object1));

Where the automatically generated copy constructor is this:

class foo {
public:
  foo(const foo& other) {
    //shallow copy other to this
  }
}

In order to get the code to do what you think it should do, you need to declare object 2 as const reference:

const foo& object2 = object1.function2(object1);
//&object2 == &object1


The line of code:

foo object2 = object1.function2(object1);

does 2 things.

  1. a reference (which happens to refer to object1) is returned from function2()
  2. the initialization of object2 creates a copy of the object returned by function2()
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜