temporary object

T

Tony Johansson

Hello!!

Assume I have a wrapper class with this definition.
class Integer
{
public:
Integer(int =0);
int get() const;
Integer& set(int);
Integer& add(const Integer&);
private:
int value_;
};

I have also some stand-alone functions se below
Now to my question the function createZero is returning an Integer object
lets call this object temp.
This temp object is received as a reference in function yuk. No copy
constructor is called therefore.
So does this mean that when yuk is eventually finishing the temp object goes
out of scope.
So the assignment from function foo to object g will be invalid because of
temp is out of scope.

//Tony

Integer createZero()
{ return Integer(0); }

const Integer& yuk(const Integer& i)
{ return i; }

void foo()
{
const Integer& g = yuk(creteZero());
cout << g.value();
}
 
V

Victor Bazarov

Tony said:
Assume I have a wrapper class with this definition.
class Integer
{
public:
Integer(int =0);
int get() const;
Integer& set(int);
Integer& add(const Integer&);
private:
int value_;
};

I have also some stand-alone functions se below
Now to my question the function createZero is returning an Integer object
lets call this object temp.
This temp object is received as a reference in function yuk. No copy
constructor is called therefore.
So does this mean that when yuk is eventually finishing the temp object goes
out of scope.

The temporary is destroyed when the reference [originally] bound to it
(the argument of 'yuk') ceases to exist, and that's at the end of the
"full expression", the left side of the initialisation of 'g'.
So the assignment from function foo to object g

It's not assignment, it's initialisation. And the function is 'yuk', not
'foo'.
will be invalid because of
temp is out of scope.

Yes. 'g' is initialised to the reference value that becomes invalid right
after that, and so does 'g'. The program has undefined behaviour.
//Tony

Integer createZero()
{ return Integer(0); }

const Integer& yuk(const Integer& i)
{ return i; }

void foo()
{
const Integer& g = yuk(creteZero());
cout << g.value();
}

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,744
Messages
2,569,483
Members
44,902
Latest member
Elena68X5

Latest Threads

Top