how to make friend function of std::make_shared()
.
I tried:
class MyClass{
public:
friend std::shared_ptr<MyClass> std::make_shared<MyClass>();
//or
//friend std::shared_ptr<MyClass> std::make_shared();
protected:
MyClass();
};
but it does not work (i'am using Visual Studio 2010 SP1)
The advantage of boost::make_shared() is that the memory for the object that has to be allocated dynamically and the memory for the reference counter used by the smart pointer internally can be reserved in one chunk.
The difference is that std::make_shared performs one heap-allocation, whereas calling the std::shared_ptr constructor performs two.
make_shared is exception-safe. It uses the same call to allocate the memory for the control block and the resource, which reduces the construction overhead. If you don't use make_shared , then you have to use an explicit new expression to create the object before you pass it to the shared_ptr constructor.
How about adding a static method to your class:
class Foo
{
public:
static shared_ptr<Foo> create() { return std::shared_ptr<Foo>(new Foo); }
private:
// ...
};
Here's a little hackaround:
class Foo
{
struct HideMe { };
Foo() { };
public:
explicit Foo(HideMe) { };
static shared_ptr<Foo> create() { return std::make_shared<Foo>(HideMe());
};
Nobody can use the public constructor other than the class itself. It's essentially a non-interface part of the public interface. Ask the Java people if such a thing has a name :-)
It doesn't work because the VC10 implementation hands off construction to an internal helper function. You can dig through the source code and friend this function if you want.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With