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)
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 are okay with delving into the internal implementation details of the compiler that you are using, for VC10/Visual C++ 2010, as @DeadMG mentioned, you can befriend the internal implementation. You'll want to befriend std::tr1::_Ref_count_obj<T>
.
I've tested this with Microsoft (R) C/C++ Optimizing Compiler Version 16.00.40219.01 for x64
The class who's internal data you want access to is the one that has to declare other classes as friends as it breaks standard encapsulation.
You cant have std::make_shared make your class a friend, and assuming you're not changing std::make_shared, it shouldn't want your class to be a friend.
So, unless I understand the question wrong - what you're asking can't be done.
精彩评论