在c++中,双冒号前的&符号是什么意思?

what does a ampersand before double colon mean in c++?

本文关键字:符号 是什么 意思 c++      更新时间:2023-10-16

我在以下由google的protobuf生成的代码中发现了这种用法。

inline void Datum::set_data(const void* value, size_t size) {
  set_has_data();
  //over here.
  if (data_ == &::google::protobuf::internal::kEmptyString) {
     data_ = new ::std::string;
  }
 data_->assign(reinterpret_cast<const char*>(value), size);
}

谢谢:-)!

这是两件完全不相关的事情,也许最好把它们看作

&(::google::protobuf::internal::kEmptyString)

&只是表示地址运算符,就像你做的那样:

int xyzzy = 7;
int *pointer_to_xyzzy = &xyzzy;

另一方面,::是全局命名空间说明符,以确保您不会开始查找当前命名空间。

例如,以下程序:

#include <iostream>
int x = 7;
namespace xyzzy {
    int x = 42;
    int getxa() { return ::x; }
    int getxb() { return x; }
}
int main() {
    std::cout << xyzzy::getxa() << 'n';
    std::cout << xyzzy::getxb() << 'n';
    return 0;
}

输出7后接42,因为getxa()函数使用全局命名空间说明符而不是xyzzy