c++ - C++0x 仍然可以使用全局运算符 new 显式分配吗?

标签 c++ c++11 new-operator

Wikipedia状态:

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.)

删除 operator new 类似于在当前 C++ 中将其设为私有(private),但没有显式使用全局 operator new,从而避免了特定于类的查找,仍然有效 C++0x?

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

我是否遗漏了草稿中的某些内容?


需要明确的是,这是有效的 C++03 和 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;
}

最佳答案

我相信你是对的,而维基百科是错的。 C++0x 草案标准将“已删除函数”(8.4p10)描述为不能以任何方式使用的函数(否则程序格式错误)。它们在与普通函数不同的范围或名称查找中没有任何作用。并且关于新表达的相关段落保持不变:

[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.

所以是的,表达式 ::new NonNewable [或::new(mem) NonNewable ] 将选择 ::operator new 的重载, 忽略函数 NonNewable::operator new ,并且不会使程序格式错误。

关于c++ - C++0x 仍然可以使用全局运算符 new 显式分配吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3802454/

相关文章:

c++ - C++11 中的 Unicode

c++ - Queue.empty() 为 false,但队列大小为 0

c++ - spoj 数组子 : O(n) Complexity Approach

python - 如何删除 Blob 边界上的单个像素?

c++继承Qt问题qstring

c++ - 具有运算符重载和模板的未解析的外部符号

c++ - 为什么 C++11 override 和 final 不是属性?

c++ - 将 operator new 和 operator delete 与自定义内存池/分配器一起使用

安卓应用 : How to create a new window?

C++ - 使用 "new"在堆上分配内存