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

标签 c++ templates destructor

以下代码在 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/

相关文章:

c++ - 模板化需求表达式

c++ - 当我不想调用析构函数时

c++ - 简单的项目不会编译

c++ - OpenGL翻译glm右侧还是左侧?

c++ - 如何专门化模板化运算符重载?

c++ - 如何为类 union 类编写析构函数

C++ 析构函数和内存分配,以及未定义的行为

c++ - 使用 QTextStream 读取正在写入的文件?

c++ - 模板类继承的子类定义错误

c++ - 如何通过专门化在具有单独声明和定义的模板化类的方法上使用 std::enable_if