为什么看起来我的物体被摧毁了两次?

时间:2014-05-22 10:01:05

标签: c++ pointers destructor

我在C ++中阅读了一些关于指针的内容,并且不应该将所有内容都创建为指针。为了更好地理解这一点,看看它是如何工作的,我写了一个小程序:

A main.cpp

#include <iostream>

#include "Master.h"

using namespace std;

int main()
{
    Master master = Master("master");

    master.printSlaves();

    return 0;
}

A Master.h

class Master
{
public:
    Master(std::string name);

    ~Master();

    void printSlaves()
    {
        _slave1.printName();
        _slave2->printName();
    }

private:
    Slave   _slave1;
    Slave   *_slave2;

    std::string _name;
};

Master.cpp

#include "Master.h"

Master::Master(std::string name)
{
    std::cout << "Master() entered." << std::endl;
    _name = name;

    _slave2 = new Slave("slave2");
    _slave1 = Slave("slave1");

    std::cout << "\t" << _name << " created." << std::endl;

    std::cout << "Master() exited." << std::endl;

}

Master::~Master()
{
    std::cout << "\t" << _name << " destroyed." << std::endl;
}

Slave.h

class Slave
{
public:
    Slave()
    {

    }

    Slave(std::string name);

    void printName()
    {
        std::cout << "my name is " << _name << std::endl;
    }

    ~Slave();

private:
    std::string _name;
};

Slave.cpp

#include "Slave.h"

Slave::Slave(std::string name)
{
    std::cout << "Slave() entered." << std::endl;

    _name = name;

    std::cout << "\t" << _name << " created." << std::endl;

    std::cout << "Slave() exited." << std::endl;


}

Slave::~Slave()
{
    std::cout << "\t" << _name << " destroyed." << std::endl;
}

我期待作为输出:

Master() entered. Slave() entered. slave2 created. Slave() exited. Slave() entered. slave1 created. Slave() exited. master created. Master() exited. my name is slave1 my name is slave2 master destroyed. slave1 destroyed.

但我得到了

Master() entered. Slave() entered. slave2 created. Slave() exited. Slave() entered. slave1 created. Slave() exited. **slave1 destroyed.** master created. Master() exited. my name is slave1 my name is slave2 master destroyed. **slave1 destroyed.**

显然我的slave1被摧毁了两次。我不明白为什么会这样,为什么甚至可能。

有人可以向我解释一下吗?

1 个答案:

答案 0 :(得分:4)

问题在于

_slave1 = Slave("slave1");

为部件Slave("slave1");创建临时奴隶,然后分配给_slave1。分配后,临时Slave对象将被销毁。

如果您编写代码

Master::Master(std::string name):_slave1("slave1")
{
 //other code
}

然后它将被创建和销毁一次。