I try to pass an std::unique_ptr
to an inherited class, which will forward it to the base class constructor (using an constructor initializer list). If the base class constructor receives an nullptr
an default-object should be constructed and assigned to the std::unique_ptr
member-variable from my base-class. But somehow I get an AccessViolation, if I try to access any elements from thestd::unique_ptr
anywhere (because it's somehow still an nullptr
- even if that should be impossible at this time).
Any ideas whats going wrong here?
#include <iostream>
#include <memory>
class C{
public:
int x;
};
class A{
public:
A(std::unique_ptr<C> c) : c(std::move(c)){
if(c == nullptr){
c = std::unique_ptr<C>(new C);
c->x = 1;
}
}
void print(){
std::cout << c->x << std::endl;
}
private:
std::unique_ptr<C> c;
};
class B : public A{
public:
B(std::unique_ptr<C> c) : A(std::move(c)){
}
};
int main(int argc, char* argv[]){
B b(nullptr);
b.print();
return 0;
}
In
A::ctor
you are using variablec
but it is not ref to class memberA::c
but ref to local variablec
which is ctor parameter. So after ctor exit theA::c
will benullptr
, so you can't dereference it inA::print
function.Possible solution is to make different names for local variable
c
name andA::c
, e.g.A::m_c
.