【问题标题】:c++ templates, static methods and constructorc++模板、静态方法和构造函数
【发布时间】:2012-12-10 14:21:07
【问题描述】:

以下代码在 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 永远不会被调用,但析构函数是?当“字符串 _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。

标签: c++ templates destructor


【解决方案1】:

你正在做的是未定义的行为。您将函数 (eat) 定义为返回类型 T,但您实际上并没有返回任何东西。这会导致分配未定义。

【讨论】:

  • 确实正确。将 eat 替换为:static T eat(int i) { T instance(string("Appel")); cout &lt;&lt; "Eat: " &lt;&lt; i &lt;&lt; endl; return instance; } 完美运行。
猜你喜欢
  • 1970-01-01
  • 2023-03-10
  • 1970-01-01
  • 1970-01-01
  • 2014-03-14
  • 1970-01-01
  • 1970-01-01
  • 2012-02-21
  • 1970-01-01
相关资源
最近更新 更多