11// construct_shared_object.hpp
22//
3+ // Written by Stephen Hewitt in 2025
4+ // GitHub repo: https://github.com/shewitt-au/std-enable_shared_from_this-and-constructors
35
46#pragma once
57/*
8+
69The motivation for this code is issues with std::shared_ptr and
710std::enable_shared_from_this.
811
@@ -12,7 +15,7 @@ Consider code like this:
1215Assume that `SomeClass`'s constructor uses shared_from_this. In this case, since
1316SomeClass is not yet owned by a std::shared_ptr, the shared_from_this call will
1417not work as expected. There seems to no way around this that I can find.
15- I wasn� t aware of this issue. It was a real kick in the pants.
18+ I wasn' t aware of this issue. It was a real kick in the pants.
1619
1720The solution implemented here is two-stage construction. First the object is
1821constructed and assigned to a std::shared_ptr; then, if present, a
@@ -22,9 +25,9 @@ The intent of the "if present" is to enable incremental migration to two-stage
2225construction on demand.
2326
2427Another issue addressed is with std::make_shared. This function requires that
25- the constructor be public. If we� re making factory methods for creation, we may
28+ the constructor be public. If we' re making factory methods for creation, we may
2629want to make the constructors non-public to stop misuse. In this case the code
27- uses std::shared_ptr� s constructor and a new call. The function that calls new
30+ uses std::shared_ptr' s constructor and a new call. The function that calls new
2831can be made a friend of the class to grant it access. We lose the advantages of
2932using std::make_shared but gain protection against incorrect object
3033instantiation.
@@ -45,7 +48,7 @@ namespace shared_object_creator {
4548 /*
4649 shared_ptr_creator is responsible for actually creating the std::shared_ptr.
4750 As described in this header's opening comment, it decides whether to use
48- std::make_shared or std::shared_ptr� s constructor and new based on the
51+ std::make_shared or std::shared_ptr' s constructor and new based on the
4952 accessibility the the class' constructor. If you wish to make the constructors
5053 non-public make this a friend. The BEFRIEND_SHARED_OBJECT_CREATOR macro can be
5154 used to do this tersely.
0 commit comments