From 03c493dd0efd8de6b5bd5bf27af63654146e4cfe Mon Sep 17 00:00:00 2001 From: Phillip Johnston Date: Wed, 27 Oct 2021 10:18:09 -0700 Subject: [PATCH] Update shared pointer example to use make_shared Fixes #29 --- examples/cpp/shared_ptr.cpp | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) diff --git a/examples/cpp/shared_ptr.cpp b/examples/cpp/shared_ptr.cpp index 9b34ad2..18d5f69 100644 --- a/examples/cpp/shared_ptr.cpp +++ b/examples/cpp/shared_ptr.cpp @@ -29,7 +29,24 @@ class SharedThing : public std::enable_shared_from_this template static std::shared_ptr create(T&&... t) { - return std::shared_ptr(new SharedThing(std::forward(t)...)); + // C++ core guidelines say we shouldn't do this: + // return std::shared_ptr(new SharedThing(std::forward(t)...)); + + // But this doesn't work because our constructor is private, and we want that + // for use with enable_shared_from_this + // return std::make_shared(std::forward(t)...); + + // So we'll make a "fake" derived class that constructs our shared thing + // using a public constructor... + struct EnableMakeShared : public SharedThing + { + EnableMakeShared(T&&... arg) : SharedThing(std::forward(arg)...) + { + } + }; + + // and use that type with make_shared + return std::make_shared(std::forward(t)...); } private: