[英]cout statement change program semantics
I have the following piece of code, which is part of a class, whose details hopefully are not important for answering that question. 我有以下一段代码,它属于类的一部分,希望它们的详细信息对于回答该问题并不重要。 I don't want an exact solution to my problem, but only an explanation, how the behavior, I'm going to describe, can occur.
我不希望确切地解决我的问题,而只是要解释一下,我将要描述的行为是如何发生的。
Character operator+(Character c) {
std::vector<float> resDensity(density);
float l;
float dh;
for (int i = 0; i < domains.size(); i++) {
for (int j = 0; j < c.domains.size(); j++) {
l = (domains[i].intersection(c.domains[j])).length();
//std::cout << l;
dh = c.density[j] * l / domains[i].length();
resDensity[i] += dh;
}
}
std::vector<Domain> h(domains);
return Character(h, resDensity);
}
You probably noticed the commented cout
statement. 您可能已经注意到了注释的
cout
语句。 Due to a numeric bug in my program, I followed the falsy value until I detected the variable l
. 由于我的程序中存在数字错误,我遵循了假值,直到我检测到变量
l
。 So I printed it to the console and found out, that the value is exactly the value I need, and also the program works just fine and the bug simply vanished. 因此,我将其打印到控制台上,发现它的值恰好是我需要的值,并且该程序也可以正常运行,并且该错误也消失了。 Uncommenting it, again, leads to the undesired misbehavior.
再次取消注释会导致意外的不良行为。
The Character
class contains the fields domains
and density
, both vector
s... Character
类包含domains
和density
字段,两个vector
都是...
The length
and intersection
method: length
和intersection
方法:
float length() {
float res;
for (int i = 0; i < is.size(); i++) {
res += is[i].b - is[i].a;
}
return res;
}
Domain intersection(Domain d) {
std::vector<Interval> hi;
for (auto i = is.begin(); i != is.end(); i++) {
for (auto j = d.is.begin(); j != d.is.end(); j++) {
hi.push_back(i->intersection(*j));
}
}
Domain hhh(hi);
return hhh;
}
I compiled the code with g++ --std=c++11 ...
我用
g++ --std=c++11 ...
编译代码g++ --std=c++11 ...
g++ --version
g++ (GCC) 4.8.2 20131219 (prerelease)
In your length()
function the res
variable is uninitialized: 在你的
length()
函数中, res
变量是未初始化的:
float res;
for (int i = 0; i < is.size(); i++) {
res += is[i].b - is[i].a; // <-- uses an uninitialized res
}
How is length()
calculated on Domain
? 如何在
Domain
计算length()
? hhh
is a local variable that you are returning, so a copy will be made. hhh
是您要返回的局部变量,因此将进行复制。 If length()
depends on something that is not copied then you will see strange behaviour. 如果
length()
依赖于未复制的内容,那么您将看到奇怪的行为。 What if you just change intersection()
to return a float or create a different method called intersectionLength()
which returns a float - do you still get the heisenbug? 如果你只是改变
intersection()
来返回一个浮点数或者创建一个名为intersectionLength()
的不同方法来返回一个浮点数 - 你还能得到heisenbug吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.