以下代码在 Food-destructor 上(/之后)崩溃;如下图所示;
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);
}
最佳答案
您正在做的是未定义的行为。您将函数 (eat
) 定义为返回类型 T
,但您实际上并没有返回 任何东西。这导致赋值未定义。
关于C++ 模板、静态方法和构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14016639/