Factory<A>() creates an unnamed temporary object which contains an A. The temporary is then destroyed, destroying the contained A as well. You then call operator() on a destroyed object, returning a pointer to an object that has been destroyed. == undefined behavior.
EDIT: What I said above is somewhat right... the destructor for the unnamed temporary of Factory<A> is called after operator() returns, leaving you with a dangling pointer. The reason the second example works is exactly because the destructor of Factory<A> does not run until after show() returns.
In some way I am impressed and convinced by your opinion. Now I believe that the cause may/should be from TEMPORARY OBJECT issue. In spite of this, I need to figure out what the behavior exactly is.
#include <iostream>
class Base{
public:
Base(){
std::cout << "Base() is called!" << std::endl;
}
virtual ~Base(){
std::cout << "~~Base() is called!" << std::endl;
}
virtualvoid show() const {
std::cout << "Base::show()!" << std::endl;
}
};
class A:public Base{
public:
A(){
std::cout << "A() is called!" << std::endl;
}
virtual ~A(){
std::cout << "~~A() is called!" << std::endl;
}
virtualvoid show() const{
std::cout << "A::show()!" << std::endl;
}
};
template<typename T>
class Factory{
public:
const T* operator()() const{
return &t;
}
Factory():t(T()){
std::cout << "Factory() is called!" << std::endl;
}
~Factory(){
std::cout <<"~~Factory() is called!" << std::endl;
}
private:
T t;
};
int main(){
const A* pA = Factory<A>()();
pA->show();
Factory<A>()()->show();
return 0;
}
Output:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
Base() is called!
A() is called!
Factory() is called!
~~Factory() is called!
~~A() is called!
~~Base() is called!
Base::show()!
Base() is called!
A() is called!
Factory() is called!
A::show()!
~~Factory() is called!
~~A() is called!
~~Base() is called!