views:

231

answers:

1

Wikipedia states:

A type can be made impossible to allocate with operator new:

struct NonNewable {
    void *operator new(std::size_t) = delete;
};

An object of this type can only ever be allocated as a stack object or as a member of another type. It cannot be directly heap-allocated without non-portable trickery. (Since placement new is the only way to call a constructor on user-allocated memory and this use has been forbidden as above, the object cannot be properly constructed.)

Deleting operator new is similar to making it private in current C++, but isn't explicitly using global operator new, which avoids class-specific lookup, still valid C++0x?

NonNewable *p = ::new NonNewable();
// neither non-portable nor trickery, though perhaps not widely known

Have I missed something in the draft?


To be clear, this is valid C++03 and works fine:

struct NonNewable {
private:
  void *operator new(std::size_t);  // not defined
};

int main() {
  // ignore the leaks, it's just an example

  void *mem = operator new(sizeof(NonNewable));
  NonNewable *p = ::new(mem) NonNewable();

  p = ::new NonNewable();

  return 0;
}
+4  A: 

I believe you are right and wikipedia is wrong. The C++0x draft standard describes "deleted functions" (8.4p10) as functions which may not be used in any way (or else the program is ill-formed). They play no part in scope or name lookup different from normal functions. And the relevant paragraphs concerning new expressions have remained the same:

[5.3.4p8] A new-expression obtains storage for the object by calling an allocation function (3.7.4.1). ...

[5.3.4p9] If the new-expression begins with a unary :: operator, the allocation function's name is looked up in the global scope. Otherwise, if the allocated type is a class type T or array thereof, the allocation function's name is looked up in the scope of T. If this lookup fails to find the name, or if the allocated type is not a class type, the allocation function's name is looked up in the global scope.

So yes, the expression ::new NonNewable [or ::new(mem) NonNewable] would choose an overload of ::operator new, ignoring the function NonNewable::operator new, and would not make the program ill-formed.

aschepler