0

我对 C++ 很陌生,但我认为我说得对,在堆栈上声明的对象应该在超出范围时自动被破坏/销毁?在我目前正在使用的迷你项目中,情况并非如此。

void MainWindow::clickTest() {
    FunkyNumber num = 4;
    FunkyNumber num2 = 6;

    num += num2;
    std::cout << num << std::endl; // This works okay!

    // Should be destroyed here!
}

我的析构函数应该这样做:

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:

#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;
}
4

2 回答 2

0

Is this in a Windows GUI application (Windows application with a WinMain entry point)?

If it is, the standard output does not get displayed automatically when running it from the command line. I am not sure why this is, but IIRC running:

myapp | cat

should cause the standard output to be setup correctly.

于 2013-10-15T16:13:26.517 回答
0

我无法重现该行为。

#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的原因不仅是为了更容易帮助您,还因为它可以帮助您自己找到问题所在(这显然不在您发布的代码中)。

于 2013-10-15T16:41:14.860 回答