gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 23:00:58 35 4
gpt4 key购买 nike

我正在阅读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/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com