returning a reference of an auto object

F

Fraser Ross

Should the A object created by func be destroyed after a B is created or
before? I'd like to know where in the standard this is described.

class A {
public:
A() {
}
~A() {
}
};

class B {
public:
explicit B(A const &) {
}
~B() {
}
};

A const & func() {
return A();
}
int main()
{
B(func());
return 0;
}
 
M

Michael Tsang

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

Fraser said:
Should the A object created by func be destroyed after a B is created or
before? I'd like to know where in the standard this is described.

class A {
public:
A() {
}
~A() {
}
};

class B {
public:
explicit B(A const &) {
}
~B() {
}
};

A const & func() {
return A();
}
int main()
{
B(func());
return 0;
}

Undefined behaviour. The temporary is discarded when the return statement
ends. (ISO/IEC 14882:2009 Section 12.2:
5 The second context is when a reference is bound to a temporary. The
temporary to which the reference is
bound or the temporary that is the complete object of a subobject to which
the reference is bound persists for the lifetime of the reference except:
(skipped)
— The lifetime of a temporary bound to the returned value in a function
return statement (6.6.3) is not
extended; the temporary is destroyed at the end of the full-expression in
the return statement.
)
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.9 (GNU/Linux)

iEYEARECAAYFAkrRvjsACgkQG6NzcAXitM9JAwCfVsVzLa2hZMo408PDhI/FodfK
bVgAn3dR1mCJj12P4Q3pihqLdFbw7zjx
=7fOQ
-----END PGP SIGNATURE-----
 
F

Fraser Ross

"Michael Tsang"
Undefined behaviour.

Is it undefined behaviour by default since I don't see anything else? I
suspected there is undefined behaviour.

Anyway thanks, that was what I was looking for.

Fraser.
 
F

Fraser Ross

The standard describes where the temporay in this case is destroyed so I
don't think there is any undefined behaviour. Different compilers issue
either a warning or an error.

Fraser.
 
B

Balog Pal

"Fraser Ross"
The standard describes where the temporay in this case is destroyed so I
don't think there is any undefined behaviour. Different compilers issue
either a warning or an error.

Returning the dongling reference is not UB. Using that reference *is* UB, as
the bound object is surely destroyed by then. So for any practical terms it
is UB, as what is a point of returning something if it is never used by the
caller?
 

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,780
Messages
2,569,611
Members
45,268
Latest member
AshliMacin

Latest Threads

Top