confused by references

T

tarmat

I'm confused by the following. I'd appreciate any advice.


//-------------------main.cpp

#include <iostream>
using namespace std;

class A
{
public:

int val;

A(int v):val(v){}
};

/////////////////////////////////////////////
class MyClass
{
private:

A& a;

public:

MyClass(A& a_):a(a_){}

int Get(){return a.val;}

};

///////////////////////////////////////////
int main()
{
MyClass mc(A(1));

cout << "\nmc.a is now " << mc.Get();

//how can mc.a be pointing to a valid integer? Isn't A(1) a
temporary?

return 0;
}


Also, if the ctor of MyClass is changed to

MyClass(A a_):a(a_){}

I get the expected result (the reference is pointing to gobbldygook).
I don't understand why, given the behavior of the first example, this
should be so.

thanks
 
R

Rob Williscroft

tarmat wrote in
class MyClass
{
private:

A& a;

public:

MyClass(A& a_):a(a_){}

int Get(){return a.val;}

};

///////////////////////////////////////////
int main()
{
MyClass mc(A(1));

cout << "\nmc.a is now " << mc.Get();

//how can mc.a be pointing to a valid integer? Isn't A(1) a
temporary?

return 0;
}


Also, if the ctor of MyClass is changed to

MyClass(A a_):a(a_){}

I get the expected result (the reference is pointing to gobbldygook).
I don't understand why, given the behavior of the first example, this
should be so.

Your first example relies on a *non-standard* feature. you are binding
a non-const reference to temporary, MS VC6 allows this and so do other
compilers that choose to operate in a VC6-compatible mode, you may be
able to give your compiler an option to increase conformance to The
C++ Standard (for e.g /Za (MS VC7.1), -pedantic and -ansi (gcc)) also
turn your compiler warnings all the way up (often -Wall).

Once you change MyClass to:

class MyClass
{
private:

A const & a;

public:

MyClass(A const & a_):a(a_){}

int Get(){return a.val;}

};

Then your example will be standard conforming, however it will also
exhibit "Undefined behaviour" (aka UB). As you correctly sumize the
temporary is destroyed at the end of the statement "MyClass mc(A(1));".
This means that its destructor (if any) will be called and the compiler
may reclaime or reuse the sorage it occupied.

In this case *Nothing* happens, the compiler doesn't release or reuse
the storage for your temporary and A's destuctor does nothing.

Note the above paragraph is pure speculation, once you write code that
exhibits UB the C++ Standard washes it hands of *all* responsability
for what happens.

Rob.
 

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

No members online now.

Forum statistics

Threads
474,147
Messages
2,570,833
Members
47,380
Latest member
AlinaBlevi

Latest Threads

Top