I have a simple program to test whether my cross product of two 3D-Vectors works.
#include <iostream>
#include "math\Vec3.h"
using namespace std;
int main(int argc, char **argv)
{
Vec3 v1(1, 23, 5);
Vec3 v2(7, 3, 4);
cout << "Crossing v1 and v2" << endl;
Vec3 v3 = v1.cross(v2);
cout << "crossed" << endl;
return 0;
}
Why was the destructor called just after creating the variable?
Here is what it printed out:
Created: Vec3[1, 23, 5]
Destroy: Vec3[1, 23, 5] // Why is the vector destroyed here?
Created: Vec3[7, 3, 4]
Destroy: Vec3[7, 3, 4] // And here?
Crossing v1 and v2
Created: Vec3[77, 31, -158]
Destroy: Vec3[77, 31, -158] //And here??
crossed
Destroy: Vec3[77, 31, -158]
Destroy: Vec3[7, 3, 4]
Destroy: Vec3[1, 23, 5]
Process returned 0 (0x0) execution time : 0.090 s
Press any key to continue.
Here is the Vec3.h:
#include <iostream>
#include <string>
struct Vec3
{
float x, y, z;
Vec3():
x(0), y(0), z(0) { std::cout << "Created: " << *this << std::endl; };
Vec3(float i, float j, float k):
x(i), y(j), z(k) { std::cout << "Created: " << *this << std::endl; };
//...
double dot(const Vec3&);
Vec3 cross(const Vec3&);
friend std::ostream& operator<<(std::ostream&, const Vec3);
//...
~Vec3();
};
Vec.cpp:
Vec3 Vec3::cross(const Vec3& v)
{
return Vec3(y * v.z - z * v.y,
z * v.x - x * v.z,
x * v.y - y * v.x);
}
std::ostream& operator<<(std::ostream& out, const Vec3 v)
{
out << "Vec3[" << v.x << ", " << v.y << ", " << v.z << "]";
return out;
}
Vec3::~Vec3()
{
std::cout << "Destroy: "
<< "Vec3[" << x << ", " << y << ", " << z << "]"
<< std::endl;
}
Your debug output (using operator<<
) causes a copy (because it takes 'Vec3' by value) and an additional destruction.
You don't provide a copy constructor, so you can't see that. But if you would, you would see that you do in fact not have more destructions than constructions.