C++变量可以在函数体中声明,但不能在类成员中声明?

发布于 2024-08-26 17:32:19 字数 199 浏览 6 评论 0原文

我想创建一个具有以下类型的 C++ 类:

  1. 它可以在函数内部声明。
  2. 它可以在成员函数内部声明。
  3. 它不能被声明为类成员。

其用途:将“根”对象视为 GC。

这在 C++ 中可能吗?特别是,我正在使用 g++。愿意改用 clang。模板或宏解决方案都可以。

谢谢!

I want to create a C++ class with the following type:

  1. It can be declared inside of a function.
  2. It can be declared inside of a member function.
  3. 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

狼亦尘 2024-09-02 17:32:19

你可以用宏来做到这一点,也许:

#define MY_TYPE \
    do { } while(0); \
    RealType

void foo() {
    MY_TYPE myvar;
    myvar.Whatever();
}

这只会在函数内部编译(因为“do ... while”位 - 尽管你会得到一个非常奇怪的错误消息)。这似乎是您想要避免的宏的“邪恶”用途之一,但是......

You could do it with a macro, perhaps:

#define MY_TYPE \
    do { } while(0); \
    RealType

void foo() {
    MY_TYPE myvar;
    myvar.Whatever();
}

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...

梦中楼上月下 2024-09-02 17:32:19

尽管我很喜欢 codeka 的答案,但我无法想象将声明作为成员属性会出现什么问题。

对于像 GC 根这样的东西,我可能会使用 Monoid 模式。该类的所有实例实际上都是Singleton 的代理(实质上),即它们都共享相同的状态。这样,实例化多少个并不重要,它们都指向相同的资源。

如果这样做是为了避免循环引用,恐怕还不够。

struct A { boost::shared_ptr<B> mB; };

struct B { boost::shared_ptr<A> mA; };

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 a Singleton (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.

struct A { boost::shared_ptr<B> mB; };

struct B { boost::shared_ptr<A> mA; };
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文