开发者

c++ static-only class allocation

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?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜