We can implement the function make_SharedPtr which will work in a similar way to std::make_shared , as long as we have a shared pointer class ready. For this example, we will use the class “SharedPtr”. SharedPtr must also have constructor (and assignment operator) from raw pointer defined.
The function uses one template parameter T which will signify the type of object being pointed to, and one template parameter pack Ts… which will forward the arguments to the object constructor.
Since std::make_shared doesn’t throw however, we need to make our version do the same thing. So we can call the new operator with (std::nothrow).
template <typename T, typename... Ts>
SharedPtr<T> make_SharedPtr(Ts... args) noexcept {
// this makes it noexcept
T *raw = new (std::nothrow) T(args...);
SharedPtr<T> ret = raw;
return ret;
}
Usage:
SharedPtr<Foo> bar = make_SharedPtr<Foo>(42);
One limitation of this implementation is using arrays, for which you would have to implement operator[] for your SharedPtr class anyway.
Leave a Reply