Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

friend function of std::make_shared() in Visual Studio 2010 (not Boost)

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)

like image 765
uray Avatar asked Sep 22 '11 21:09

uray


People also ask

What is boost :: Make_shared?

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.

What is difference between Make_shared and shared_ptr?

The difference is that std::make_shared performs one heap-allocation, whereas calling the std::shared_ptr constructor performs two.

What is Make_shared?

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.


2 Answers

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 :-)

like image 131
Kerrek SB Avatar answered Sep 17 '22 10:09

Kerrek SB


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.

like image 42
Puppy Avatar answered Sep 21 '22 10:09

Puppy