C++ c++;模板、静态方法和构造函数
以下代码在食品销毁器上(/之后)崩溃;如下面的堆栈所示C++ c++;模板、静态方法和构造函数,c++,templates,destructor,C++,Templates,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> >::~
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
6运算符删除()0xb7e5f4bf
5 std::string::_Rep::_M_destroy()0xb7ec648b
4 0xb7ec64d0
3 std::basic_string::~basic_string()0xb7ec653e
2食品::~Food()Main.cpp:126 0x0804c33c
1 main()main.cpp:199 0x0804c288
食物破坏者从未被调用,但破坏者是?当“string\u text”的资源被释放时,事情会变得一团糟,但我似乎不明白为什么会出错。
显然,我可以将“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);
}
类食品{
私人:
字符串-文本;
公众:
食物(){
cout您正在做的是未定义的行为。您将函数(eat
)定义为返回类型T
,但实际上没有返回任何内容。这会导致赋值未定义。您正在做的是未定义的行为。您定义了函数(eat
)作为返回类型T
,但实际上没有返回任何内容。这导致赋值未定义。您的程序甚至没有为我编译,因为static T eat(int i)
没有返回它应该返回的T
。您的程序甚至没有为我编译,因为static T eat(int i)
没有返回它应该返回的T
。确实正确。将eat替换为:static T eat(inti){T instance(string(“Appel”);确实正确。将eat替换为:static T eat(inti){T instance(string(“Appel”);cout