Home > Mobile >  C : Variables change values after initialization of different class
C : Variables change values after initialization of different class

Time:11-27

I have the following problem.

PerspectiveCamera pcam2(Point(0, 0, 0), Vector(0.5f, 0.5f, 0.3f), Vector(0, 0, 1), pi * 0.9f, pi * 0.9f);
Renderer r12(&pcam2,0);

In the above code, pcam2 is initialized and then after that, &pcam2 is passed on to r12.

pcam2 has members const Point& center, const Vector& forward, const Vector& up, and two float numbers that are passed upon initialization in said order.

r12 has members Camera* cam_ and an int number.

The strange thing that happens is that during the initialization of r12, the values of the field center of pcam2 get changed to some bogus like Point(1.984192e 27, 4.59149455e-41, 0) when in the code you can see that pcam2 was initialized with Point(0, 0, 0). Literally all that happens during initialization of r12 is that its members are assigned their values via member initialization list.

I really don't understand what is happening here and I don't know enough about C to find out on my own.

Thanks in advance.

CodePudding user response:

Point(0, 0, 0) is a temporary object which lives only until the nearest ;. If you store a reference to it inside pcam2, this reference becomes dangling right after the line with pcam2 initialization is complete. Any access to the dangling reference afterwards is undefined behavior.

You typically don't need to store any references in structs, having ownership semantics (i.e. storing by-value and copying/moving data into struct) is less errorprone and easier to reason about.

  • Related