What i know
I know that returning a const reference to a temporary object is fine! (e.g. this example :)
class A { public: virtual const A& clone () { return (A()); } virtual std::string name() const { return ("A"); } };
Returning a temporary object and binding to a const reference
But!
If I wanted to do this, it's still correct:
class B : public A { public: virtual const A& clone () { return (B()); } virtual std::string name() const { return ("B"); } };
I would have thought yes, but at runtime, the returned object is still treated as object A (as in this example :)
main.cpp
#include <iostream> #include <string> int main() { B bb; A* aa = &bb; std::cout << aa->clone().name() << std::endl; }
Output
valgrind ./a.out ==14106== Use of uninitialised value of size 8 ==14106== at 0x401BF9: main (main.cpp:8) ==14106== Uninitialised value was created by a stack allocation ==14106== at 0x401BF2: main (main.cpp:8) B
This is a B .. yay .. but this warning is pretty terrifying ....
Edit
Thank you, I know, I see my mistake ... but I would like to know some other things about this ...
When this is done, what exactly happens on the stack?
source share