成员变量在赋值后保存垃圾值

问题描述 投票:0回答:1

我遇到了一个奇怪的场景,我无法弄清楚它为什么会发生。

我有一个简单的int成员的对象。

className.h文件:

private:
  int       m_variable;

public:
                   ...
(constructor and the rest of the functions)  
                   ...

className.cpp文件:

void className::function()
{
    ...
    m_variable = pointerToOtherClass->getMaxDistOfAllMatrices(); //first call
    int x = pointerToOtherClass->getMaxDistOfAllMatrices();     //second call
    m_variable = x;

    cout << m_variable  << "," << x;
}

第一个呼叫和第二个呼叫的功能是相同的,即将返回相同的值。

当我在第一次调用时放置断点并跳过调用时,我看到m_variable hols junk和x持有4(预期结果)。线m_variable = x;没有任何改变(x=4m_variable仍然保留垃圾)和cout之后它打印4,4这是预期的。

first call的线,是代码第一次遇到m_variable

我不明白为什么会这样,我在这里做错了什么?

c++ class debugging compiler-optimization
1个回答
1
投票

您正在看到优化工件。将函数getMaxDistOfAllMatrices()的第一个结果存储到变量m_variable被省略,因为稍后第一次调用函数的第二次调用的结果的两行再次存储到该变量(通过x)。

x保留了预期值,因为它稍后在cout中使用。请注意,调用的函数不会被省略(调用两次),因为它可能有副作用,但忽略第一个结果是有效的。

m_variable = ponterToOtherClass->getMaxDistOfAllMatrices(); //first call

踩到上面的线后,你可能会看到m_variable的垃圾。

int x = ponterToOtherClass->getMaxDistOfAllMatrices();     //second call
m_variable = x;

在踩到两行以上后,您会看到两个变量中的预期值。

© www.soinside.com 2019 - 2024. All rights reserved.