struct A
{
A(int a);
};
struct B
{
B();
void b(std::shared_ptr<A> a);
};
int main()
{
A a(1);
B b;
b.b(&a);
}
So I got this error, sorry guys it’s my frist time with the smart pointers!!
Error:
no suitable constructor exists to convert from
"A *"to"std::tr1::shared_ptr<A>"
How do I fix this problem!?
Others already ranted on the design error of your code, but not the real problem why the code doesn’t even compile.
shared_ptrhas a constructor that accepts a raw pointer, but it is marked asexplicit, which means you have to explicitly write out that you want to construct ashared_ptrinstance. What your function call tries, is to do that construction implicitly, which isn’t allowed because of the explicit keyword.The following will compile but give undefined behaviour because the
shared_ptrwill (try to)deletean object which resides on the stack and is as such not deleteable:A special trait of
shared_ptris that you can pass the constructor a deleter, which will be called when the owned pointer should be deleted. You can just write and use a “noop” deleter, which does just nothing; the following will not invoke undefined behaviour and will not try to delete the stack variable:And there actually is a use for this, if you have a library API that absolutely wants a
shared_ptrbut you want to call it with a stack variable. The design of that API is another thing though…