c++仅静态类分配
我知道如何防止类的堆分配(使 new 和 new[] 私有)。 我知道如何防止堆栈和静态分配(使析构函数私有)。
我想知道是否有办法在编译时只允许静态分配?
I know how to prevent heap allocation of a class (make new and new[] private).
I know how to prevent stack and static allocations (make destructor private).
I am wondering is there anyway to allow only static allocations at compile time?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
没有。对不起。原因是静态分配对类型的要求与自动分配完全相同;是无法区分的。
但是,您可以阻止客户端代码实例化您的类型,并提供对由该类型自己的代码创建的一个或多个实例的访问。
一般来说,人们经常认为单例等是一个很棒的想法,也许它给人一种掌控感,无论如何,但无论如何,随后发生的事情是在某些时候需要更通用的实例化,并且所有这些工作不仅仅是浪费但随后会积极地产生更多……而且是完全不必要的……工作。
所以一般建议是,对于过早的优化,不要这样做。
尽管在某些情况下这可能是正确的解决方案。
干杯&呵呵,
Nope. Sorry. Reason is that the static allocation places exact same requirements on the type as automatic allocation; it can't be distinguished.
However, you can prevent client code from instantiating your type, and provide access to one or more instances created by the type's own code.
Generally people often think that singletons etc. are a splendid idea, perhaps it confers some feeling of being in control, whatever, but anyway, what then happens is that at some point more general instantiation is needed, and all that work was not just wasted but then actively generates more … and completely needless … work.
So general advice is, as for premature optimization, don't do it.
Although in some cases it can be the right solution.
Cheers & hth.,
为什么不直接使用命名空间呢?如果您只想拥有某个东西的静态实例,则没有理由将其包装在类中。
Why not just use a namespace? There's no reason to wrap something in a class if you're only ever going to have a static instance of it.
没有办法强制类的所有实例都是静态的。您可以创建一个仅包含静态成员的类吗?
在我看来,这比使用
命名空间
更好,因为命名空间不能有私有成员。There is not a way to force all instances of a class to be static. Could you create a class with exclusively static members instead?
In my opinion, this is better than using a
namespace
, because namespaces cannot have private members.