reference to the temporary object

R

Raider

is such code correct?

#include <string>
typedef std::string T;

T *s;

const T& foo(const T& default)
{
if (s) return *s; else return default;
}

int main()
{
const T& value = foo("bar");
// use value
}

I think the "bar" must be destroyed immediatly when foo() returns.
 
F

Frederick Gotham

Raider posted:
is such code correct?

#include <string>
typedef std::string T;

T *s;

const T& foo(const T& default)
{
if (s) return *s; else return default;
}


"default" is a keyword in C++.


const T &foo(const T &def)
{
if(s) return *s;

return def;
}

int main()
{
const T& value = foo("bar");
// use value
}

I think the "bar" must be destroyed immediatly when foo() returns.

Step 1: A non-const, nameless, R-value temporary is created.
Step 2: It is passed by const reference to a function.
Step 3: The function then returns it by const reference.
Step 4: The calling function binds a reference named "value" to the
returned reference.

If you bind a reference to a temporary, the temporary's lifetime is
extended to that of the reference. However, there's only one Step in
which this happens: Step 1. The argument to the function gets destroyed
once the function returns. The function returns an invalid reference.
You're left with a reference to an invalid object.
 
F

Frederick Gotham

Raider posted:
Frederick, thanks for support. I get it.


(Some gentle advice: If you top-post here, a lot of people will ignore
you.)

It's nice to try write code to prove things... I do it all the time! Take
this for example:

(Unchecked code)

class ArbitraryClass
{
public:

bool is_valid;

ArbitraryClass() : is_valid(true) {}

~ArbitraryClass() { is_valid = false; }
};


#include <cstdlib>


const ArbitaryClass &Func( const ArbitraryClass &arg )
{
static ArbitraryClass obj;

if ( std::rand() == 52 ) return obj;

return arg;
}

#include <iostream>

int main()
{
const Arbitrary &ref = Func( ArbitraryClass() );

std::cout << "Is the object referred to by ref valid? "
<< ( ref.is_valid ? "true" : "false" );

}
 

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
473,743
Messages
2,569,478
Members
44,898
Latest member
BlairH7607

Latest Threads

Top