[英]Strange vector initialization issue
I recently debugged a strange C++ problem, in which a newly declared vector somehow had a size of 477218589. Here's the context: 我最近调试了一个奇怪的C ++问题,其中新声明的向量以某种方式具有477218589的大小。这是上下文:
struct Triangle {
Point3 a,b,c;
Triangle(Point3 x, Point3 y, Point3 z) : a(x), b(y), c(z) {}
Vector3 flat_normal() { return (a-c)^(b-c); }
};
vector<Triangle> triangles;
Calling triangles.size()
returns the value 477218589
. 调用
triangles.size()
返回值477218589
。 I 'fixed' the problem by changing struct Triangle
to class Triangle
, but I'm wondering why there's any difference. 我通过将
struct Triangle
更改为struct Triangle
class Triangle
来“解决”该问题,但我想知道为什么会有任何区别。 Should I have done that typedef struct Foo { ... } Foo;
我应该完成
typedef struct Foo { ... } Foo;
magic? 魔法? If so, why would that help?
如果是这样,为什么会有帮助?
If it matters, I'm using g++-4.1. 如果有关系,我正在使用g ++-4.1。
There shouldn't be any difference between declaring Triangle
as a struct or class - in C++, the difference between the two is that the default access specification of the members is public for struct and private for class, but that's it. 将
Triangle
声明为结构或类之间应该没有任何区别-在C ++中,两者之间的区别在于,成员的默认访问规范对于struct是公共的,对于类是private的,仅此而已。
Is there anything more to Triangle
that you didn't include? 除了
Triangle
还有其他您没有包括的内容吗?
This 这个
#include <vector>
#include <iostream>
struct Point3 {};
struct Triangle {
Point3 a,b,c;
Triangle(Point3 x, Point3 y, Point3 z) : a(x), b(y), c(z) {}
};
int main()
{
std::vector<Triangle> triangles;
std::cout << triangles.size() << '\n';
return 0;
}
prints 0
for me. 为我打印
0
。 If it also does for you, then the problem is in parts of the code not included in this snippet. 如果它也对您有用,那么问题出在此代码片段未包含的部分代码中。 If it prints anything else, something is fishy with your compiler/std lib/setup.
如果打印出其他任何内容,则说明您的编译器/ std lib / setup有问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.