If the argument passed in to the function is supposed to always be a weak_ptr
-version of this you have a problem. There is nothing in the code enforcing this behaviour, so a user of your class could just as easily pass a weak_ptr to another object of class X
.
If what you need is for bar2
to be able to pass on a shared_ptr
to this
, a better solution is to use std::enable_shared_from_this
Example
#include <iostream>
#include <memory>
struct Foo : public std::enable_shared_from_this<Foo> {
Foo() { std::cout << "Foo::Foo\n"; }
~Foo() { std::cout << "Foo::~Foo\n"; }
std::shared_ptr<Foo> getFoo() { return shared_from_this(); }
};
int main() {
Foo *f = new Foo;
std::shared_ptr<Foo> pf1;
{
std::shared_ptr<Foo> pf2(f);
pf1 = pf2->getFoo(); // shares ownership of object with pf2
}
std::cout << "pf2 is gone\n";
}
Output:
Foo::Foo
pf2 is gone
Foo::~Foo
from http://en.cppreference.com/w/cpp/memory/enable_shared_from_this/shared_from_this