繁体   English   中英

C ++堆栈分配的变量未破坏(/已销毁?)

[英]C++ stack allocated variable not destructed (/destroyed?)

我对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;
}

这是否在Windows GUI应用程序(具有WinMain入口点的Windows应用程序)中?

如果是这样,则从命令行运行标准输出时不会自动显示它。 我不确定为什么会这样,但是IIRC正在运行:

myapp | cat

应导致正确设置标准输出。

我无法重现该行为。

#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 ,不仅是为了更轻松地为您提供帮助,而且还因为它可以帮助您找到问题所在(显然不在发布的代码中)。

暂无
暂无

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

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