Error with Google Mock and shared_from_this?
-
19-04-2021 - |
Question
I'm getting the following error thrown in a test of mine:
unknown file: error: C++ exception with description "tr1::bad_weak_ptr" thrown in the test body.
Stepping through the test one line at a time I can see the exception is being thrown on a line where I call:
MyClassSharedPointer myClassPointer(shared_from_this());
I need a pointer to the object the code is executing in, because I need to set the object up as an observer of one of it's members (using boost::signals to implement the observer). The code appears to work fine while normally executing but from my test code I get this error.
Solution
The problem was that in my production code the myClass object is referenced as a shared_ptr whereas in my test code I had mistakenly declared the myClass object as a naked pointer. Which explains why shared_from_this()
wasn't working... because this
wasn't actually a shared_ptr.
OTHER TIPS
For me the issue was that myClass did not have a shared_ptr
prior to shared_from_this
being called (it was being used in a unique_ptr
). And shared_from_this
requires that at least one shared_ptr
must already have been created. See also this answer.