7

可以向 C++ 用户定义的文字运算符传递空指针吗?

这确实发生在 g++ 的实验版本(gcc 版本 4.7.0 20111114 (experimental) [trunk revision 181364] (Debian 20111114-1))中,但我不确定这是一个错误(90% 肯定)还是一些奇怪的预期行为。

示例程序:

#include <iostream>
#include <stdexcept>
#include <string>

std::string operator "" _example (const char * text) {
  using std::cerr;
  using std::endl;
  cerr << "text (pointer) = " << static_cast<const void *>(text) << endl;
  if (!text) throw std::runtime_error("Is a null pointer really expected?");
  cerr << "text (string) = \"" << text << '"' << endl;
  return text;
}

int main() {
  2_example;
  1_example;
  0_example;
}

输出(可能是 gcc 中的一个错误......但也许不是?!,因此问题):

text (pointer) = 0x8048d49
text (string) = "2"
text (pointer) = 0x8048d4b
text (string) = "1"
text (pointer) = 0
terminate called after throwing an instance of 'std::runtime_error'
  what():  Is a null pointer really expected?
Aborted

这不仅仅是“0_example”;每当文字值为零时。例如,即使文字是“0x0000_example”,它仍然会发生。

这是一个错误吗?或者当文字的值为零时一些奇怪的特殊情况?

4

1 回答 1

5

正如 Alf P. Steinbach 在一个很好的评论中向我保证的那样,这是一个错误,而不是标准行为(没什么大不了的,因为我使用的是 gcc 快照)。

我去提交了一个 gcc 错误,但看起来它已经在上游提交并修复了:

http://gcc.gnu.org/bugzilla/show_bug.cgi?id=50958

于 2011-12-05T01:04:42.240 回答