0

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.

4

2 回答 2

3

构造函数需要设置dynamic为 false,然后new您需要一个静态方法,而不是覆盖,例如:

static message *createMessage(int _id)
{
    message *ret = new message(_id);
    ret->dynamic = true;
    return ret;
}

然后调用该方法而不是newing a message

于 2013-07-30T22:50:12.217 回答
3

不要这样做。除了它不能工作之外,一个对象不应该管理任何关于它自己的生命周期的事情。您可以使用unique_ptrorshared_ptr与自定义删除器,如果对象是堆栈分配的,您可以在其分配站点知道;在这种情况下,您可以提供一个无操作删除器,如下所示:

struct null_deleter {
  template<class T>
  void operator()(const T*) const {}
};
于 2013-07-30T22:55:03.217 回答