C++:何时以及为何调用析构函数?

标签 c++ destructor destroy

我有一个简单的程序来测试我的两个 3D vector 的叉积是否有效。

#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;
}

最佳答案

您的调试输出(使用 operator<< )导致复制(因为它按值获取“Vec3”)和额外的销毁。

你没有提供复制构造函数,所以你看不到它。但如果你愿意,你会发现实际上破坏并不多于 build 。

关于C++:何时以及为何调用析构函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15703836/

相关文章:

Perl 5.14 神秘的拼写错误错误消息、DESTROY 和 AUTOLOAD

c++ - 类数据成员的销毁顺序?

c++ - std::string 在 vi​​sual studio 上的具体行为?

c++ - 在 C++ 中反转通用双向链表

c++ - 如何在 ns3 中使用属性

c++ - 继承中的析构函数

c++ - 默认虚拟驱动器

node.js - Sequelize如何返回被破坏的行

mysql错误: can't destroy an object that is created using factoryGirl

c++ - 内存重用不当导致的未定义行为