bad_weak_ptr when using shared_from_this in ctor

Hi,

When I run the example program below (just a MVP of my actual issue), I get a bad_weak_ptr exception. I'd suppose it has something to do with the fact that `this` for `Resource` isn't fully created yet by the time we're calling shared_from_this? But that's just a guess, since if I put it not-in-the-constructor, I think all is well.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <iostream>
#include <memory>

class Resource : public std::enable_shared_from_this<Resource>
{
public:
	Resource() { std::cout << shared_from_this() << std::endl; }
	~Resource() {}

private:
	int i;
};

class Wrapper
{
public:
	Wrapper()
	: m_resource{new Resource()} { }
	~Wrapper() {}

private:
	std::shared_ptr<Resource> m_resource;
};

int main()
{
	Wrapper m_wrapper;
}


Output:
libc++abi.dylib: terminating with uncaught exception of type std::__1::bad_weak_ptr: bad_weak_ptr
Abort trap: 6

Is there a viable way to get a shared_ptr to an object in the object's constructor?
You can only call shared_from_this() once the object is being managed by an std::shared_ptr. While inside the constructor, new hasn't even returned yet, let alone had its return value assigned to any std::shared_ptrs. So in other words, there's no way to call shared_from_this() from the same object's constructor.

More generally, calling this->shared_from_this() from the class is risky, because the object might not have even been allocated on the heap and you have no control over that inside the class. If someone allocates an instance of the class on the stack and then calls a member function that for whatever reason calls shared_from_this(), you'll run into the same issue.
Thanks! Good point about having no control over the objects allocation...
Topic archived. No new replies allowed.