c++ - 为什么 sgi STL 源代码在 operator new 函数前面使用双冒号?

标签 c++ stl

我正在阅读SGI标准模板库的源代码。我发现 operator new 函数前面总是有一个双冒号。像这样:

T* tmp = (T*)(::operator new((size_t)(size * sizeof(T))));

operator new可以不加::字段直接调用,那为什么STL coder会这样写呢?如果我们不使用它们前面的::,可能会遇到什么陷阱或情况。

最佳答案

您可以为类重载 operator new 并在其前面加上 "::"将调用全局 "default"operator new 而不是可能的重载。例如:

#include <iostream>

class Foo
{
public:
  Foo() { std::cout << "Foo::Foo()" << std::endl; }

  void * operator new(size_t )
  { 
    std::cout << "Foo::operator new()" << std::endl; 
    return static_cast<Foo *>(malloc(sizeof(Foo)));
  }
};


int main()
{
  Foo foo;
  std::cout << "----------------------" << std::endl;
  Foo * p = new Foo;
  std::cout << "----------------------" << std::endl;
  Foo * q = ::new Foo;
}

将打印

Foo::Foo()
----------------------
Foo::operator new()
Foo::Foo()
----------------------
Foo::Foo()

编辑:截断的代码确实不是关于在类范围内定义的 operator new。一个更好的例子是:

#include <iostream>

namespace quux {

void * operator new(size_t s)
{
  std::cout << "quux::operator new" << std::endl;
  return malloc(s);
}

void foo()
{
  std::cout << "quux::foo()" << std::endl;
  int * p = static_cast<int*>(operator new(sizeof(int)));
}

void bar()
{
  std::cout << "quux::bar()" << std::endl;
  int * p = static_cast<int*>(::operator new(sizeof(int)));
}

} // namespace quux


int main()
{
  quux::foo();
  quux::bar();
}

打印出来的

quux::foo()
quux::operator new
quux::bar()

关于c++ - 为什么 sgi STL 源代码在 operator new 函数前面使用双冒号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22829631/

相关文章:

c++ - 为什么在 free 之后引用对象时没有段错误?

C++ STL 算法 : get pointers of elements in container

c++ - 这两种比较STL vector 的方法有什么区别?

c++ - 类型转换或调用仿函数为函数指针?

c++ - Boost 测试设置错误 : memory access violation

c++ - 如何在 Windows 中以编程方式查找动态加载的模块(静态模块)

c++ - 重载迭代器 : C++ Semantics Question

c++ - C++中有排序集合吗?

c++ - STL map Custom Key Class [默认构造函数]

c++ - 为什么静态大小的数组类型不能是容器类型?