Temporary Variables: Temporaries Are Not Necessarily Evil - Binding a reference to a temporary object
(Page 2 of 4 )
It is clear that the lifetime of a temporary object is exactly that… temporary. For the same reason, it is not possible to return a pointer or reference to a local object -- because its lifetime is temporary. So beware and stay clear of the following type of code:
MyClass& partyCrasher(void) {
(void)printf(“party crasher called!\n”);
MyClass localCrasher(“partyCrasher”);
return localCrasher;
}
MyClass &crasher=partyCrasher();
crasher.shout();
(void)printf(“Done!\n”);
But what if the returned object is a temporary variable?
MyClass anotherPartyCrasher(void) {
(void)printf(“another party crasher called!\n”);
return MyClass(“anotherPartyCrasher”);
}
MyClass &crasher=anotherPartyCrasher();
anotherPartyCrasher.shout();
(void)printf(“Done!\n”);
Lets examine what the compiler is generating by reusing the MyClass class from the first article:
#include <stdio.h>
class MyClass {
char const *mName;
public:
MyClass(char const *name) : mName(name) {
(void)printf(“%s created.\n”, mName);
}
MyClass(MyClass const &other) : mName(“unseen gatecrasher”) {
(void)printf(“%s copied from %s\n”, mName, other.mName);
}
~MyClass() {
(void)printf(“%s destroyed.\n”);
}
void shout() const {
(void)printf(“%s shouts:‘Crash the party!’\n”, mName);
}
};
First we try the partyCrasher function:
party crasher called!
partyCrasher created.
partyCrasher destroyed.
¿³? shouts:’Crash the party!’
Done!
Hopefully your compiler has generated a warning about returning the address of a local variable or temporary in this function. It is wise to heed your compiler’s warnings, as this shows that only a fool would ignore them.
The output makes it clear that the partyCrasher was destroyed before it was used. This is all as we expected.
Here is what happens when we try anotherPartyCrasher function:
another party crasher called!
anotherPartyCrasher created.
AnotherPartyCrasher shouts:’Crash the party!’
Done!
AnotherPartyCrasher destroyed.
Lo and behold! Apparently the temporary object is only destroyed when it leaves the scope of the function where it was created for an expression that needed it. This behavior is actually guaranteed by the C++ Standard, so it is fine to bind a reference to a temporary object as long as you only use it in the same scope it was created in.
Next: Death by Returned const Reference >>
More C++ Articles
More By J. Nakamura