struct Abstract{
virtual void methodA() = 0;
};
struct Test : public Abstract{
virtual void methodA(){
printf("Test message");
}
};
class Foo{
Abstract* abs; //I made it this way so that an instance of Foo
//can easily switch between any class that implements
//Abstract
public:
virtual ~Foo(){
delete abs; //free abs
}
void setAbs(Abstract* a){
abs = a; //is there any other way to do this?
}
void changeAbs()//method to switch abs
void show(){
abs->methodA();
}
};
int main(){
Test *test = new Test();
// Test test; //local instantiation will throw a segmentation fault
//because abs is freed in the desctructor of Foo
Foo foo;
foo.setAbs(test);
foo.show();
// delete test; //using a pointer is fine unless freed
return 0;
}
我的擔憂是:指針和抽象類
如果我不免費ABS在析構函數和用戶忘記釋放他的目標實現摘要,或者如果用戶做這種方式
setAbs(new Test())
,會有泄漏。如果我釋放在析構函數ABS它會拋出一個分段錯誤,如果用戶實例本地測試或他用一個指針,並刪除它最終自己。
Abstract abs
也是不允許的,因爲它是一個抽象類
我想改變setAbs(),以這樣的:
void setAbs(Abstract* a){
abs = new Abstract(*a); //but copying like a normal class doesn't work on abstract classes
}
我的問題是,是否有任何其他方式實現setAbs(),以便它將傳遞參數的副本?
如果沒有其他辦法,我只是讓freeing成爲用戶的工作。
呃,'std :: shared_ptr'? – 2013-03-07 04:09:54
請注意,'Abstract'沒有虛擬析構函數,所以'delete abs'會產生未定義的行爲。 – 2013-03-07 14:20:15