On 4/6/20 4:34 AM, Martin Liška wrote:


May I please ping Jason, Nathan and Jonathan who can help us here?

On IRC Martin clarified the question as essentially 'how do you pair up operator new and operator delete calls?' (so you may delete them if the object is not used).

I am not sure you're permitted to remove those calls in general. All I can find is [expr.new]/12 'An implementation is allowed to omit a call to a replaceable global allocation function (17.6.2.1, 17.6.2.2). When it does so, the storage is instead provided by the implementation or provided by extending the allocation of another new-expression.'

But, I suspect the optimization is safe, in that either no one counts objects by their allocation, or if they do, they don't actually care that the std-conforming number of allocations happen.

The both operator new and operator delete are looked up in the same manner. The std does not require a 'matching pair' be found. but it is extremely poor form for a class to declare exactly one of operator {new,delete}.

The following is well formed:

struct PoorForm {
  void *operator new (size_t s) {count++; return ::operator new (s)};
  static unsigned count;
};

Have you considered throwing ctors?

struct Obj {
  Obj (); // might throw
};

'obj = new Obj (); ... delete obj;' sequence expand to something like ...

// obj = new Obj ();
void *p = ::operator new (sizeof (Obj));
try {
  Obj::ctor(p);
}
catch (...) // cleanup code
{
  ::operator delete (p); // #1
  throw;
}

obj = (Obj*)p;

.... user code

// delete obj;
Obj::dtor (obj);
::operator delete (obj); // #2

calls 1 & 2 matchup to the operator new call

Notice that para I quoted allows one to coalesce allocations using the global operator new/deletes. The rules are pretty much as you can guess -- one lifetime must be entirely within the other. If inner one's ctor throws, the exception path must destroy the outer.

does that help?

nathan

--
Nathan Sidwell

Reply via email to