我遇到了一个奇怪的场景,我无法弄清楚它为什么会发生。
我有一个简单的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=4
,m_variable
仍然保留垃圾)和cout
之后它打印4,4
这是预期的。
first call
的线,是代码第一次遇到m_variable
。
我不明白为什么会这样,我在这里做错了什么?
您正在看到优化工件。将函数getMaxDistOfAllMatrices()
的第一个结果存储到变量m_variable
被省略,因为稍后第一次调用函数的第二次调用的结果的两行再次存储到该变量(通过x
)。
x
保留了预期值,因为它稍后在cout
中使用。请注意,调用的函数不会被省略(调用两次),因为它可能有副作用,但忽略第一个结果是有效的。
m_variable = ponterToOtherClass->getMaxDistOfAllMatrices(); //first call
踩到上面的线后,你可能会看到m_variable
的垃圾。
int x = ponterToOtherClass->getMaxDistOfAllMatrices(); //second call
m_variable = x;
在踩到两行以上后,您会看到两个变量中的预期值。