I have a simple C++ class for which I need to know whether an object should be delete'd or not at a certain point in my program. The mechanism should be portable across platforms and modern C++ compilers.
One way of doing it I can think of is: have a member field which is not initialized by the constructor but instead is assigned by the overloaded operator new, like so:
class message
{
protected:
    int id;
    bool dynamic;
public:
    message(int _id): id(_id)
    {
        // don't touch `dynamic` in the constructor
    }
    void* operator new(size_t size)
    {
        message* m = (message*)::operator new(size);
        m->dynamic = true;
        return m;
    }
    void operator delete(void* m)
    {
        if (((message*)m)->dynamic)
            ::operator delete(m);
    }
};
Apart form that it "feels" wrong, what is wrong with this method?
Edit: should have mentioned that the object is either dynamic or static (and never stack-local) and thus is guaranteed to be either zeroed or initialized with new.