C++ stack allocated variable not destructed (/destroyed?)
我对 C 语言很陌生,但我认为我说得对,在堆栈上声明的对象应该在超出范围时自动销毁/销毁?在我目前正在使用的迷你项目中,情况并非如此。
1 2 3 4 5 6 7 8 9 | void MainWindow::clickTest() { FunkyNumber num = 4; FunkyNumber num2 = 6; num += num2; std::cout << num << std::endl; // This works okay! // Should be destroyed here! } |
我的析构函数应该这样做:
1 2 3 4 | virtual FunkyNumber::~FunkyNumber() { std::cout <<"goodbye cruel world! (" << m_intValue <<")" << std::endl; // m_intValue is just the int value of this"FunkyNumber" } |
但是标准输出没有任何结果!
可能应该提到我正在使用 Qt - 但这只是一个普通的 C 类,所以从我能看出的情况来看这并不重要...
编辑:
funkynumber.cpp:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | #include"funkynumber.h" FunkyNumber::FunkyNumber(int num) : m_intValue(num) { std::cout <<"made a funkynumber" << num << std::endl; } FunkyNumber::~FunkyNumber() { std::cout <<"goodbye cruel world! (" << m_intValue <<")" << std::endl; } int FunkyNumber::intValue() const { return m_intValue; } void FunkyNumber::operator+=(const FunkyNumber &other) { m_intValue += other.intValue(); } void FunkyNumber::operator=(const FunkyNumber &other) { m_intValue = other.intValue(); } bool FunkyNumber::operator==(const FunkyNumber &other) { return other.intValue() == m_intValue; } std::ostream &operator<<(std::ostream &outStream, const FunkyNumber &num) { outStream <<"FunkyNumber (" << num.intValue() <<")"; return outStream; } |
我无法重现该行为。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 | #include<iostream> struct FunkyNumber{ int m_intValue; FunkyNumber::FunkyNumber(int num) : m_intValue(num) { std::cout <<"made a funkynumber" << num << std::endl; } FunkyNumber::~FunkyNumber() { std::cout <<"goodbye cruel world! (" << m_intValue <<")" << std::endl; } int FunkyNumber::intValue() const { return m_intValue; } void FunkyNumber::operator+=(const FunkyNumber &other) { m_intValue += other.intValue(); } void FunkyNumber::operator=(const FunkyNumber &other) { m_intValue = other.intValue(); } bool FunkyNumber::operator==(const FunkyNumber &other) { return other.intValue() == m_intValue; } }; std::ostream &operator<<(std::ostream &outStream, const FunkyNumber &num) { outStream <<"FunkyNumber (" << num.intValue() <<")"; return outStream; } void call(){ FunkyNumber num = 4; FunkyNumber num2 = 6; num += num2; std::cout << num << std::endl; // This works okay! // Should be destroyed here! } int main(int argc, char **argv){ call(); std::cout <<"call ended" << std::endl; } |
这很好用。人们推广 SSCCE 的原因不仅是为了更容易帮助您,还因为它可以帮助您自己找到问题所在(这显然不在您发布的代码中)。
这是在 Windows GUI 应用程序中吗(带有
如果是,从命令行运行时标准输出不会自动显示。我不确定这是为什么,但 IIRC 正在运行:
1 | myapp | cat |
应该可以正确设置标准输出。