‘ std: ;’在 c + + 中会做什么?

我最近修改了一些代码,在函数的一行中发现了一个已经存在的 bug:

std:;string x = y;

该代码仍在编译,并且一直按预期工作。

字符串定义可以工作,因为这个文件是 using namespace std;,所以首先不需要 std::

问题是,为什么 std:;要编译,它在做什么?

2312 次浏览

std: its a label, usable as a target for goto.

As pointed by @Adam Rosenfield in a comment, it is a legal label name.

C++03 §6.1/1:

Labels have their own name space and do not interfere with other identifiers.

It's a label, followed by an empty statement, followed by the declaration of a string x.

Its a label which is followed by the string

(expression)std: (end of expression); (another expression)string x = y;

The compiler tells you what is going on:

#include <iostream>
using namespace std;
int main() {
std:;cout << "Hello!" << std::endl;
}

Both gcc and clang give a pretty clear warning:

std.cpp:4:3: warning: unused label 'std' [-Wunused-label]
std:;cout << "Hello!" << std::endl;
^~~~
1 warning generated.

The take away from this story: always compile your code with warnings enabled (e.g. -Wall).