The following code fails to compile in Visual C++ 11 with this error:
1>c:\users\tony\documents\visual studio 11\projects\cpp11_ex1\cpp11_ex1\main.cpp(52): error C2440: ” : cannot convert from ‘Foo *const ‘ to ‘std::weak_ptr<_Ty>’
#include <stdio.h>
#include <memory>
using namespace std;
class Foo;
class Bar
{
public:
Bar( weak_ptr<Foo> foo ) : _foo(foo) { printf("Bar(%p)\n",this); }
~Bar() { printf("~Bar(%p)\n",this); }
private:
weak_ptr<Foo> _foo;
};
class Foo
{
public:
Foo() : _bar() { _bar = make_shared<Bar>( weak_ptr<Foo>(this) ); printf("Foo(%p)\n",this); }
~Foo() { printf("~Foo(%p)\n",this); }
private:
shared_ptr<Bar> _bar;
};
int main( int argc, char* argv[] )
{
shared_ptr<Foo> instance = make_shared<Foo>();
return 0;
}
It seems that I can’t create a weak_ptr from a raw this pointer. This causes an interesting series of problems.
-
Since I am attempting this in
Foo‘s ctor,Foo‘s reference count is 0 (i.e. themake_shared<>in main hasn’t returned yet). -
I’ve discovered that I can create
weak_ptrs fromshared_ptrs… But if I changeBarctor to take ashared_ptr, I the act of callingBar‘s constructor ends up destroyingFoo! (SinceFoo‘s reference count is still 0, creating (and then destroying) ashared_ptrtoFoovia a call toBar‘s ctor ).
All I really want to do is create Foo, have Foo create and own a Bar, but have Bar have a weak reference back to Foo. I really don’t want to be forced into 2 part initialization here!
Since
Foowill be pointed at by a shared_ptr, and Bar will always be owned by a shared_pointer of Bar, then if Bar exists, Foo exists. Ergo, you don’t need a smart pointer in Bar. (If I understand the problem correctly)