单行注释延续

Single line comment continuation

来自 C++ 标准(至少回到 C++98)§ 2.2,注释 2 状态:

Each instance of a backslash character (\) immediately followed by a new-line character is deleted, splicing physical source lines to form logical source lines. Only the last backslash on any physical source line shall be eligible for being part of such a splice. Except for splices reverted in a raw string literal, if a splice results in a character sequence that matches the syntax of a universal-character-name, the behavior is undefined. A source file that is not empty and that does not end in a new-line character, or that ends in a new-line character immediately preceded by a backslash character before any such splicing takes place, shall be processed as if an additional new-line character were appended to the file.

并且,第 2.7 节指出:

The characters /* start a comment, which terminates with the characters */. These comments do not nest. The characters // start a comment, which terminates with the next new-line character. If there is a form-feed or a vertical-tab character in such a comment, only white-space characters shall appear between it and the new-line that terminates the comment; no diagnostic is required. [Note: The comment characters //, /*, and */ have no special meaning within a // comment and are treated just like other characters. Similarly, the comment characters // and /* have no special meaning within a /* comment. ]

我将这两个放在一起表示以下内容:

// My comment \
is valid

// My comment \ still valid \
is valid

在 C++98 中是合法的。在 GCC 4.9.2 中,这些都在没有任何诊断消息的情况下编译。在 MSVC 2013 中,它们都会产生以下内容:

warning C4010: single-line comment contains line-continuation character

如果您启用了警告作为错误(我这样做了),这将导致程序无法成功编译(没有警告作为错误,它工作得很好)。标准中是否有不允许单行注释延续的内容,或者这是 MSVC 不符合标准的情况?

这不是合规问题。您已明确要求编译器将有效构造视为错误,这就是它的作用。

如果您指定 -Wcomment-Wall.

,GCC 将给出相同的警告(或错误,如果需要)

我会说 MS 对以下事实很敏感:

#define macro() \
    some stuff \
    // Intended as comment \
    more stuff

然后在代码中使用 macro() 时会出现非常有趣的错误。

或者其他只是不小心输入了这样的评论:

// The files for foo-project are in c:\projects\foo\
int blah;

(出现 "undefined variable blah" 的奇怪错误)

我绝不会在单行注释中使用续行,但如果您有充分的理由,只需在 MSVC 中关闭该警告即可。

也正如 Mike 所说:标准甚至没有涵盖警告 - 它只说明需要成为错误的内容。如果启用 "warnings are errors",您将不得不选择启用哪些警告,或者接受某些技术上有效(但可疑)的构造在构建中将不被接受,因为编译器制造商已决定发出警告关于它。尝试在 gcc 或 clang 中编写 if (c = getchar()),看看在 "high" 上有多少 -Werror 和警告。然而,根据标准,它是完全有效的。