Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why does sgi stl source code use the double-colon in front of the operator new function?

Tags:

c++

stl

I am reading the source code of SGI standard template library. I find that the operator new function always has a double-colon in front of it. Like this:

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

operator new can be directly called without adding the :: field, then why do the stl coders write it in this way? What trap or situation may it come to if we don't use the :: in front of them.

like image 737
richard.g Avatar asked Apr 03 '14 06:04

richard.g


1 Answers

You can overload operator new for a class and prefixing it with "::" will call the global "default" operator new instead of a possible overload. For example:

#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;
}

will print

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

Edit: The code snipped is indeed not about operator new that is defined in a class scope. A better example would be this:

#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();
}

which prints

quux::foo()
quux::operator new
quux::bar()
like image 73
MadScientist Avatar answered Sep 25 '22 12:09

MadScientist