我有一个库,它们都是通过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