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

后端 未结 15 2220
有刺的猬
有刺的猬 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:37

    A way for MFC classes:

    .H

    class CTestNEW : public CObject
    {
    public:
        bool m_bHasToBeDeleted;
        __declspec(thread) static void* m_lastAllocated;
    public:
    #ifdef _DEBUG
        static void* operator new(size_t size, LPCSTR file, int line) { return internalNew(size, file, line); }
        static void operator delete(void* pData, LPCSTR file, int line) { internalDelete(pData, file, line); }
    #else
        static void* operator new(size_t size) { return internalNew(size); }
        static void operator delete(void* pData) { internalDelete(pData); }
    #endif
    public:
        CTestNEW();
    public:
    #ifdef _DEBUG
        static void* internalNew(size_t size, LPCSTR file, int line)
        {
            CTestNEW* ret = (CTestNEW*)::operator new(size, file, line);
            m_lastAllocated = ret;
            return ret;
        }
    
        static void internalDelete(void* pData, LPCSTR file, int line)
        {
            ::operator delete(pData, file, line);
        }
    #else
        static void* internalNew(size_t size)
        {
            CTestNEW* ret = (CTestNEW*)::operator new(size);
            return ret;
        }
    
        static void internalDelete(void* pData)
        {
            ::operator delete(pData);
        }
    #endif
    };
    

    .CPP

    #include "stdafx.h"
    .
    .
    .
    #ifdef _DEBUG
    #define new DEBUG_NEW
    #endif
    
    void* CTestNEW::m_lastAllocated = NULL;
    CTestNEW::CTestNEW()
    {
        m_bHasToBeDeleted = (this == m_lastAllocated);
        m_lastAllocated = NULL;
    }
    

提交回复
热议问题