简体   繁体   中英

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:

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 . I 'fixed' the problem by changing struct Triangle to class Triangle , but I'm wondering why there's any difference. Should I have done that typedef struct Foo { ... } Foo; magic? If so, why would that help?

If it matters, I'm using 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.

Is there anything more to Triangle that you didn't include?

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM