C++ Templates

H

huangshan

hi all:

i am reading "C++ Templates: The Complete Guide"

in "2.4 Overloading Function Templates",
he say "This is because for C-strings, max(a,b) creates a new, temporary
local value that may be returned by the function by reference."

i can't understand that why in this condition will becomes an error.
 
V

Victor Bazarov

huangshan said:
i am reading "C++ Templates: The Complete Guide"

in "2.4 Overloading Function Templates",
he say "This is because for C-strings, max(a,b) creates a new,
temporary local value that may be returned by the function by
reference."
i can't understand that why in this condition will becomes an error.

Returning a reference to a [local] temporary object is something you
should consider avoiding since the reference will outlive the object
and will become invalid before the function even returns it. Any
use of that reference will have undefined behaviour.

V
 
Y

Ye Dafeng

huangshan said:
can you give me a example ?

thanks

char* getVoid()
{
char temp = 'c';

return &temp;
}

in this example, the temp address may be used for other object. If you
use it, you will get another result which you do not expect.
 
M

Martin Steen

huangshan said:
can you give me a example ?

thanks

Don't do this:

int& Function1()
{
int a = 100;
return a; // g++ warning: reference to local variable 'a' returned
// When Function1 ends, the reference to a is no longer
// valid, because a is local.
}

void Function2()
{
cout << Function1() << endl;
// output is not "100", but something else!
}

Best regards,
-Martin
 
G

Greg Comeau

char* getVoid()
{
char temp = 'c';

return &temp;
}

in this example, the temp address may be used for other object. If you
use it, you will get another result which you do not expect.

Right, as Victor mentioned, temp is not guaranteed to exist once
getVoid is over with. Therefore, to return its adress to be used
as if it still exists is asking for trouble. This is another facet
of something I term "good garbage" because it is something that
may appear to work, but use that pointer 10 minutes lates and
it may not be pointing at temp any longer but some other variable
which has taken its place, and so on.
 
L

loufoque

Ye said:
char* getVoid()
{
char temp = 'c';

return &temp;
}

This is not what he asked for.
What he asked for is :

char& getVoid()
{
char temp = 'c';

return temp;
}
 

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,768
Messages
2,569,575
Members
45,053
Latest member
billing-software

Latest Threads

Top