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.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With