我有一个简单的程序来测试我的两个 3D 向量的叉积是否有效。
#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;
}
为什么在创建变量后立即调用析构函数?
这是它打印出来的:
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.
这是 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;
}