简体   繁体   中英

Aliasing in C++

In C++, I've always known the intialization of Foo& f = _f; to create an alias to the member _f . So, from that point on I can call f and it's just like I was calling _f .

I have tried doing this where I am setting an alias to the return of a getter function, and it doesn't seem to be working. How come? This is what I'm trying..

Foo &f = c->getFoo(); //where I have a pointer c that points to an object of type Foo.

Without seeing the declaration, I assume that the problem you have is that you can't get a non const reference for a temporary. So

Foo const&f = c->getFoo();

but

Foo f(c->getFoo());

would probably work as well.

doing Foo &f = c->getFoo() is not an alias. It actually stores the returning address of getFoo() in a reference (Gives you the same object as getFoo() is returning).

It depends on the return type of getFoo(). For example, if your getFoo() returns a Foo& it would work. If your getFoo() returns a const Foo&, then you'll have to do Foo const &f = getFoo().

However, in both cases, you have to make sure that the object returned by getFoo is available in the class c scope, not only in the getFoo() scope (Check that it's not a temporary).

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