我有一個庫,它們都是通過Google測試套件全面測試的。我試圖保持它「乾淨」,但我遇到了段錯誤,我無法弄清楚。嘗試訪問庫中成員的函數時出現Segfault錯誤
相關代碼:
Interface.h:
class Interface{
public:
Interface();
void Function(const int argument);
private:
std::unique_ptr<Implementation> Implement;
std::unique_ptr<DependencyInjection> Injection1, Injection2;
};
Interface.cpp:
Interface::Interface()
: Injection1(new DependencyInjection()),
Injection2(new DependencyInjection()),
Implement(new Implementation(*Injection1, *Injection2)) {}
void Interface::Function(const int argument){ Implement->Function(argument); }
Implementation.h:
class Implementation{
public:
Implementation(AbstractInjection &injection1, AbstractInjection &injection2);
void Function(const int argument);
private:
AbstractInjection Injection1, Injection2;
};
Implementation.cpp
Implementation::Implementation(AbstractInjection &injection1, AbstractInjection &injection2)
: Injection1(injection1),
Injection2(injection2) {}
void Implementation::Function(const int argument){
injection1.Function(argument); } // code from here out is all well tested and works
因此,當我創建接口並調用Interface.Function()時,代碼段錯誤會嘗試評估Implementation.Function()。我已經通過我能想到的一切運行gdb,所有的指針都是非空的。
如果我只是創建一個測試,看起來像
std::unique_ptr<DependencyInjection1> injection1(new DependencyInjection());
std::unique_ptr<DependencyInjection2> injection2(new DependencyInjection());
std::unique_ptr<Implementation> implement(new Implementation(*injection1, *injection2));
implement->Function(0);
的代碼工作正常,並沒有出現段錯誤
但如果我創建像
Interface iface;
iface.Function(0);
測試就會段錯誤。
我是新來的整個unique_ptr的東西,但我懷疑是不是更大的問題。這可能是一隻紅鯡魚,我不知道。
-Edit:Nope,我有他們在錯誤的順序畢竟。對不起,那是對的!謝謝一堆!測試現在通過。 (之前的評論):對不起,我在代碼中以正確的順序排列了它們,但是我沒有在我的帖子中以正確的順序編寫它們。 – shavera
@Alex我想說你的界面可能不應該擁有Injection1和Injection2,你需要製作兩個注入類的副本。當您在執行調用中分配給您的「AbstractInjection」實例時,您也會得到切片。 – IdeaHat
是的,當我將它複製到這裏時,這更像是抽象的人工產物。它更像是A類; B類:A類;和X,Y:B類,Z類:A。然後實現有一個構造函數(B,B,A)並且接口注入(X,Y,Z)。在測試它的情況下(MockX,MockY,MockZ) – shavera