Skip to content

Instantly share code, notes, and snippets.

@wenjinghuan999
Created October 18, 2022 09:17
Show Gist options
  • Save wenjinghuan999/b59ae24b297f773c5e138a1966a45712 to your computer and use it in GitHub Desktop.
Save wenjinghuan999/b59ae24b297f773c5e138a1966a45712 to your computer and use it in GitHub Desktop.
Use passkey idiom when you want enable_shared_from_this to use make_shared
#include <memory>
class A : public std::enable_shared_from_this<A> {
private:
struct key{ explicit key() = default; };
public:
static std::shared_ptr<A> create() {
return std::make_shared<A>(key{});
}
explicit A(key) {}
};
int main() {
auto a1 = A::create();
// auto a2 = std::make_shared<A>();
// auto a3 = std::shared_ptr<A>(new A());
// A a4;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment