Can a C++ class determine whether it's on the stack or heap?

后端 未结 15 2218
有刺的猬
有刺的猬 2020-12-13 04:14

I have

class Foo {
....
}

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

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


        
15条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-13 04:30

    The meta question as asked by pax is asked "why would you want to do that" you'll likely get a more informative answer.

    Now assuming you're doing this for "a good reason" (perhaps just curiousity) can get this behaviour by overriding operators new and delete, but don't forget to override all 12 variants including:

    new, delete, new no throw, delete no throw, new array, delete array, new array no throw, delete array no throw, placement new, placement delete, placement new array, placement delete array.

    One thing you can do is put this in a base class and derive from it.

    This is kind of a pain, so what different behavior did you want?

提交回复
热议问题