下面的代碼崩潰(/之後)食物析構函數;如下面的堆棧所示;C++模板,靜態方法和構造函數
6 operator delete() 0xb7e5f4bf
5 std::string::_Rep::_M_destroy() 0xb7ec648b
4 <symbol is not available> 0xb7ec64d0
3 std::basic_string<char, std::char_traits<char>, std::allocator<char> >::~basic_string() 0xb7ec653e
2 Food::~Food() Main.cpp:126 0x0804c33c
1 main() Main.cpp:199 0x0804c288
Food-ctor永遠不會被調用,但析構函數是?當「string _text」的資源被釋放時,AFAICT的東西變得無用,但我似乎無法理解爲什麼這會出錯。 很顯然,我可以將「string _text」更改爲「string * _text」,但我寧願明白爲什麼會出錯。
class Food {
private:
string _text;
public:
Food(){
cout << "ctor Food" << endl;
}
Food(string name) {
cout << "ctor Food: name=" << name << endl;
}
virtual ~Food() {
cout << "dtor Food" << endl;
}
};
template<typename T>
class Action {
public:
static T eat(int i) {
cout << "Eat: " << i << endl;
}
};
int main() {
auto x = Action<Food>::eat(1);
}
你的程序甚至不會爲我編譯,因爲'static T eat(int i)'不會返回它應該設置的'T'。 – user93353