C++变量可以在函数体中声明,但不能在类成员中声明?
我想创建一个具有以下类型的 C++ 类:
- 它可以在函数内部声明。
- 它可以在成员函数内部声明。
- 它不能被声明为类成员。
其用途:将“根”对象视为 GC。
这在 C++ 中可能吗?特别是,我正在使用 g++。愿意改用 clang。模板或宏解决方案都可以。
谢谢!
I want to create a C++ class with the following type:
- It can be declared inside of a function.
- It can be declared inside of a member function.
- It can not be declared as a class member.
The use of this: think "Root" objects for a GC.
Is this possible in C++? In particular, I'm using g++. Willing to switch to clang. Either templates or macro solution fine.
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你可以用宏来做到这一点,也许:
这只会在函数内部编译(因为“do ... while”位 - 尽管你会得到一个非常奇怪的错误消息)。这似乎是您想要避免的宏的“邪恶”用途之一,但是......
You could do it with a macro, perhaps:
This would only compile inside a function (because of the "do ... while" bit - though you'd get a really weird error message). It seems like one of those "evil" uses of macros that you would want to avoid, however...
尽管我很喜欢 codeka 的答案,但我无法想象将声明作为成员属性会出现什么问题。
对于像 GC 根这样的东西,我可能会使用 Monoid 模式。该类的所有实例实际上都是
Singleton
的代理(实质上),即它们都共享相同的状态。这样,实例化多少个并不重要,它们都指向相同的资源。如果这样做是为了避免循环引用,恐怕还不够。
Even though I gotta love
codeka
's answer, I cannot but imagine what the problem is with a declaration as a member attribute.For something like a GC's root I would probably use the
Monoid
Pattern. All instances of the class are in fact proxies to aSingleton
(in essence), ie they all share the same state. This way it doesn't matter how many are instantiated, they all point to the same resource.If you do so to avoid cyclic references, I am afraid it's not nearly enough.