returning reference of a member variable

N

Naren

Hi ,
Is it correct to return reference of a member variable.
because it can be like we have already deleted the object and still
holding the reference
of member variable.


A *a = new A;
int & r = a.get(); // int& A::get() { //returning a member of class
A}
delete a;
cout<<r;
 
R

Rolf Magnus

Naren said:
Hi ,
Is it correct to return reference of a member variable.
Yes.

because it can be like we have already deleted the object and still
holding the reference of member variable.

Well, you have to ensure that this doesn't happen.
A *a = new A;
int & r = a.get(); // int& A::get() { //returning a member of class
A}
delete a;
cout<<r;

That would invoke undefined behavior.
 
G

Greg

Naren said:
Hi ,
Is it correct to return reference of a member variable.
because it can be like we have already deleted the object and still
holding the reference
of member variable.


A *a = new A;
int & r = a.get(); // int& A::get() { //returning a member of class
A}
delete a;
cout<<r;

Another problem with returning a non-const reference to a member is
that the client can then use it to change the value of the object's
member variable directly - instead of having to go through the proper
channels (which would be the object's class interface).

Greg
 
K

korusef

Rolf said:
Naren wrote:
...

That would invoke undefined behavior.

And what if I use
int const& r = a.get(); //int const& A::get()

will it still be undefined behavior?
 
V

Victor Bazarov

And what if I use
int const& r = a.get(); //int const& A::get()

will it still be undefined behavior?

What's different here? 'a' is not a temporary, A::get returns
a reference, not a temporary. As soon as 'a' is destroyed, all
of its contents is gone, and any reference to any part of 'a'
becomes invalid. Using it has UB.

V
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,767
Messages
2,569,572
Members
45,045
Latest member
DRCM

Latest Threads

Top