0
我正在進行這個單元測試。我想刪除鑽頭和電池,但似乎不起作用(也許電池不能被刪除)。我可以在析構函數上做任何事情來處理這個問題嗎?如何刪除C++中連接另一個對象的對象?
void test_rover::testDisconnectBattery() {
Drill* drill = new Drill();
drill->connectBattery(new Battery(10));
drill->disconnectBattery();
//CPPUNIT_ASSERT(drill->Connected()==false);
delete drill;
CPPUNIT_ASSERT(Object::getCount()==0);
}
Device.cpp(設備是鑽基部)
Device::Device() {
}
Device::Device(const Device& copy) {
}
Device::~Device() {
delete _battery;
}
void Device::connectBattery(Battery *b){
_battery = b;
}
void Device::disconnectBattery(){
_battery = NULL;
}
Battery.cpp
Battery::Battery(int power) {
_power = power;
}
Battery::Battery(const Battery& copy) {
}
Battery::~Battery() {
}
int Battery::Power(){
return _power;
}
當析構函數('〜Device')被調用,'_battery'爲'NULL'時,您需要在斷開連接或外部連接時刪除電池 –
使用std :: unique_ptr –
您正在使用C++,爲什麼你不使用std :: shared_ptr或std :: unique_ptr,因爲它適合? – Nandu