【发布时间】:2020-05-07 07:21:39
【问题描述】:
多年来我不得不回来使用 c++。我有点生疏了,谁能解释一下在主函数中构造和解构对象时发生了什么。
代码按预期工作。奇怪的是,如果我调试代码,调试器会在构造类时停止执行两次,在销毁时停止执行 3 次。但它停在代码的一部分,其中没有调试信息是可离开的(是的 gcc 正在生成我的调试信息)。我想对此进行调查,但我不确定代码的真正作用。
这是代码:
class LSPI_BusSymulation_SlaveDevice;
class LSPI_BusSymulation{
public:
LSPI_BusSymulation(uint16_t dataSizePerDevice, uint16_t maxNumberOfDevices, uint16_t actualNumberOfDevices);
private:
uint16_t actualNumberOfDevices;
std::vector<LSPI_BusSymulation_SlaveDevice> devices;
std::vector<uint8_t> recvData;
};
class LSPI_BusSymulation_SlaveDevice{
public:
LSPI_BusSymulation_SlaveDevice(uint16_t processDataSizePerDevice, uint16_t maxNumberOfDevices);
private:
uint16_t dataSizePerDevice;
std::vector<uint8_t> data;
};
LSPI_BusSymulation::LSPI_BusSymulation(uint16_t dataSizePerDevice, uint16_t maxNumberOfDevices, uint16_t actualNumberOfDevices)
: actualNumberOfDevices(actualNumberOfDevices){
recvData.resize(dataSizePerDevice * (maxNumberOfDevices + 1));
devices.assign(actualNumberOfDevices, LSPI_BusSymulation_SlaveDevice(dataSizePerDevice, maxNumberOfDevices));
}
LSPI_BusSymulation_SlaveDevice::LSPI_BusSymulation_SlaveDevice(uint16_t processDataSizePerDevice, uint16_t maxNumberOfDevices)
: dataSizePerDevice(processDataSizePerDevice){
data.resize(processDataSizePerDevice * (maxNumberOfDevices + 1 + 1));
}
int main(){
LSPI_BusSymulation busSymulation(10, 10, 10);
return 0;
}
对我来说重要的问题是:(但如果你有时间一步一步的解释也会有所帮助)
LSPI_SYMULATION_SLAVE_DEVICE 的构造函数和析构函数多久被调用一次?
是否所有对象都存储在 busSymulation.devices 中,并且将对象与自己的内存分开?
向量 busSymulation.devices[n].data 是否也被复制或设备共享一个数据向量?
【问题讨论】:
-
@freakish 确定我做到了。但我不确定我是否理解正确。对于分配:我认为,分配了一个 const 对象。然后多次复制该对象。所以构造函数被调用一次。当这个向量被删除时, obecjts 析构函数被调用 vector.size() + 1 次。但我不太确定。一切正常,但调试器的行为很奇怪,这让我觉得我理解错了。
标签: c++ class vector constructor