block 内声明的对象的 C++ 持久性,内存泄漏的可能性?

标签 c++ class object block instantiation

首先让我在这个问题前加上以下几点: 1) 我已经在 Stackexchange 上搜索了这个问题,所提供的大部分代码对我来说都很难理解,以保证就此提出一个新问题/打开一个新线程。我能找到的最接近的是这个 Creating multiple class objects with the same name? c++不幸的是,这超出了我的理解范围

2) http://www.cplusplus.com/doc/tutorial/classes/没有真正讨论过这个或者我已经错过了。

现在这已经不在了:

矩形类代码:

class Rectangle {
private:
    int lineNumber;
    float valueMax;
    float valueMin;
public:
    Rectangle(SCStudyInterfaceRef sc, int lineNumber, float valueMax, float valueMin);
    int getLineNumber(); // member function of class
    float getValueMax(); // member function of class Rectangle
    float getValueMin(); // member function of class Rectangle
};

Rectangle::Rectangle(SCStudyInterfaceRef sc, int lineNumber0, float value1, float value2) {
    lineNumber = lineNumber0;
    int value2_greater_than_value1 = sc.FormattedEvaluate(value2, sc.BaseGraphValueFormat, GREATER_OPERATOR, value1, sc.BaseGraphValueFormat); 
    if (value2_greater_than_value1 == 1) {
        valueMax = value2;
        valueMin = value1;
    } else {
        valueMax = value1;
        valueMin = value2;
    }
}

int Rectangle::getLineNumber() {
    return lineNumber;
}

float Rectangle::getValueMax() {
    return valueMax;
}

float Rectangle::getValueMin() {
    return valueMin;
}

这里是更重要的部分,这段代码几乎是在循环中运行,并且会在每次特定事件触发时重复:

bool xxx = Conditions here

if (xxx) { 
// Draw new rectangle using plattforms code
code here

// Save rectangle information in the list:
Rectangle rect(sc, linenumbr + indexvalue, high, low);
(*p_LowRectanglesList).push_back(rect);
} 

bool yyy = conditions here

if (Short) { 
// Draw new rectangle using plattforms code
code here

// Save rectangle information in the list:
Rectangle rect(sc, linenumber + indexvalue, high, low);
(*p_HighRectanglesList).push_back(rect);

所以问题如下:

由于每次事件触发时都会循环执行代码的第二部分,因此将检查 bool 条件,如果为真,则将使用平台集成代码绘制矩形。一旦绘制完成,此信息将被传递到基于代码第一部分中的 Rectangle 类的新矩形对象/实例,使用:Rectangle rect(sc, linenumber + indexvalue, high, low) ; 部分,然后将该信息保存在一个列表中,该列表暂时位于代码的不同部分并且无关紧要。

当有一个新的 Bool = True 条件并且代码在它已经执行之后被执行时究竟会发生什么?旧的矩形对象是否会简单地替换为具有相同名称并使用新参数的新矩形对象(因为由于代码的编写方式,它们在每个实例上都会发生变化)?或者现在是否有两个使用相同名称“rect”的 Rectangle 类对象?

从技术上讲,这对我来说甚至没有那么重要,因为无论如何都应该使用 (*p_HighRectanglesList).push_back(rect); 部分代码将参数信息推送到列表中

所以 TL;DR: “rect”是否被破坏/覆盖,或者现在可能有无限数量的称为“rect”的矩形对象/实例漂浮在周围?

我为文字墙道歉,但作为一个完全的菜鸟,我认为最好概述我的思考过程,这样您就可以更轻松地纠正我的错误。

亲切的问候, 轨道

最佳答案

是的,rect 在每个循环中都会被销毁并重新创建。在 C++ 中, block 中声明的任何变量的范围(在本例中为 if() 语句)仅限于该 block 。每次你的程序迭代时,你都会得到一个新的 rect,而旧的 rect 就不见了。

关于 block 内声明的对象的 C++ 持久性,内存泄漏的可能性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17682487/

相关文章:

c++ - 我应该删除一个指针吗?

c++ - 我的代码的第二部分没有运行,我是使用类的新手

java - 没有字段的类是否有特殊名称?

c++ - 将 Win32 应用程序转换为对象

c++ - 无论如何都要避免浮点运算导致最大在线点数问题

c++ - C++ 模板只是 "grammar safe"并且首先不是类型安全的?

python - Python 3中套接​​字的子类中的WinError 10038

python - 如何将类实例分配给变量并在其他类中使用它

android - Android 中导航或对象跟踪应用程序中使用的 map 是什么?

c++ - 如何将 SetFocus 设置为 CButton 以便边框和焦点虚线可见?