一个C ++类可以确定它是在栈还是堆? [英] Can a C++ class determine whether it's on the stack or heap?

查看:86
本文介绍了一个C ++类可以确定它是在栈还是堆?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有

class Foo {
....
}

Foo有能力分离出来的方法:

Is there a way for Foo to be able to separate out:

function blah() {
  Foo foo; // on the stack
}

function blah() {
  Foo foo* = new Foo(); // on the heap
}

我希望Foo能够做不同的事情

I want Foo to be able to do different things depending on whether it's allocated on the Stack or the Heap.

编辑:

Alof的人问我为什么这样?

Alof of people have asked me "why do this?"

答案:

我现在使用ref计数GC。但是,我想有能力运行mark&扫过。为此,我需要标记一组根指针 - 这些是堆栈上的指针。因此,对于每个类,我想知道它们是在堆栈还是在堆中。

I'm using a ref-counted GC right now. However, I want to have ability to run mark & sweep too. For this, I need to tag a set of "root" pointers -- these are the pointers on the stack. Thus, for each class, I'd like to know whether they're in the stack or in the heap.

推荐答案

需要实际问我们真正的问题:-)很明显,你为什么认为这是必要的,但它几乎肯定不是。事实上,这几乎总是一个坏主意。

You need to actually ask us the real question :-) It's apparent to you why you think this is necessary but it almost certainly isn't. In fact, it's almost always a bad idea.

为什么你认为你需要这样做?

Why do you think you need to do this?

我通常发现它是因为开发人员希望根据分配的位置删除或不删除对象,但这通常应该留给代码的客户端,而不是你的代码本身。

I usually find it's because developers want to delete or not delete the object based on where it was allocated but that's something that should usually be left to the client of your code rather than your code itself.

更新:

你所要求的很少领域是有意义的。理想情况下,您将覆盖所有内存分配和取消分配运算符,以跟踪创建和从堆中删除的内容。

Apologies, you've probably found one of the few areas in which what you're asking makes sense. Ideally, you'd override all the memory allocation and de-allocation operators to keep track of what is created and removed from the heap.

但是,我不确定这是一个简单的事情拦截新/删除的类,因为可能会有 delete 没有被调用的情况下,由于标记/扫描依赖于引用计数,你需要

However, I'm not sure it's a simple matter of intercepting the new/delete for the class since there could be situations where delete is not called and, since mark/sweep relies on a reference count, you need to be able to intercept pointer assignments for it to work correctly.

您是否考虑过如何处理这个问题?

Have you thought about how you're going to handle that?

经典示例:

myobject *x = new xclass();
x = 0;

不会导致删除调用。

另外,如何检测到您的实例的指针在堆栈上的事实?拦截新的和删除可以让你存储对象本身是堆栈还是基于堆,但我失去了如何告诉指针将被分配到哪里,特别是像下面这样的代码:

Also, how will you detect the fact that the pointer to one of your instances is on the stack? The interception of new and delete can let you store whether the object itself is stack or heap-based but I'm at a loss as to how you tell where the pointer is going to be assigned to, especially with code like:

myobject *x1 = new xclass();  // yes, calls new.
myobject *x2 = x;             // no, it doesn't.

这篇关于一个C ++类可以确定它是在栈还是堆?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆