问题
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)
回答1:
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 :-)
回答2:
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.
回答3:
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
回答4:
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.
来源:https://stackoverflow.com/questions/7521660/friend-function-of-stdmake-shared-in-visual-studio-2010-not-boost