问题描述
我有这段代码不起作用,但我认为意图很明确:
I have this code that doesn't work, but I think the intent is clear:
testmakeshared.cpp
但是我编译的时候出现这个错误:
But I get this error when I compile it:
这条消息基本上是说,::std::make_shared
模板实例化堆栈中的一些随机方法无法访问构造函数,因为它是受保护的.
This message is basically saying that some random method way down in the template instantiation stack from ::std::make_shared
can't access the constructor because it's protected.
但我真的想同时使用 ::std::make_shared
并防止任何人创建一个 ::std::shared_ptr 没有指向的这个类的对象.有什么办法可以做到这一点吗?
But I really want to use both ::std::make_shared
and prevent anybody from making an object of this class that isn't pointed at by a ::std::shared_ptr
. Is there any way to accomplish this?
推荐答案
这个答案 可能更好,我可能会接受.但我也想出了一个更丑陋的方法,但仍然让一切仍然是内联的并且不需要派生类:
This answer is probably better, and the one I'll likely accept. But I also came up with a method that's uglier, but does still let everything still be inline and doesn't require a derived class:
编辑 2017-01-06: 我对此进行了更改,以明确表示此想法可以清楚且简单地扩展到接受参数的构造函数,因为其他人正在提供这些方面的答案并且似乎对这个.
Edit 2017-01-06: I changed this to make it clear that this idea is clearly and simply extensible to constructors that take arguments because other people were providing answers along those lines and seemed confused about this.
这篇关于如何在只有受保护或私有构造函数的类上调用 ::std::make_shared?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!
本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!