我在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
被摧毁了两次。我不明白为什么会这样,为什么甚至可能。
有人可以向我解释一下吗?
答案 0 :(得分:4)
问题在于
行_slave1 = Slave("slave1");
为部件Slave("slave1");
创建临时奴隶,然后分配给_slave1
。分配后,临时Slave
对象将被销毁。
如果您编写代码
Master::Master(std::string name):_slave1("slave1")
{
//other code
}
然后它将被创建和销毁一次。