简体   繁体   English

C ++模板,静态方法和构造函数

[英]c++ templates, static methods and constructor

Following code crashes on(/after) the Food-destructor; 以下代码在Food-destructor上(/之后)崩溃; as shown in the stack below; 如下面的堆栈所示;

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    

The Food-ctor is never called but the destructor is? Food-ctor从未被调用过,而析构函数是? AFAICT things go haywire when resources of "string _text" are being freed, but I can't seem to understand why this is going wrong. 当释放“字符串_text”的资源时,AFAICT变得一团糟,但我似乎无法理解为什么这是错误的。 Obviously I could change "string _text" to "string* _text", but I'd rather understand why this goes wrong. 显然,我可以将“ 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);
}

What you are doing is undefined behavior . 您正在执行的操作是未定义的行为 You define a function ( eat ) as returning a type T , but you are not actually returning anything. 您将一个函数( eat )定义为返回类型T ,但实际上没有返回任何内容。 This leads to the assignment being undefined. 这导致分配未定义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM