C用户定义的文字运算符是否可以传递空指针?

前端之家收集整理的这篇文章主要介绍了C用户定义的文字运算符是否可以传递空指针?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
C用户定义的文字运算符是否可以传递空指针?

这实际上发生在g的实验版本(gcc版本4.7.0 20111114(实验性)[主干版本181364](Debian 20111114-1))但我不确定这是否是一个错误(90%肯定)或一些奇怪的预期行为.

示例程序:

  1. #include <iostream>
  2. #include <stdexcept>
  3. #include <string>
  4.  
  5. std::string operator "" _example (const char * text) {
  6. using std::cerr;
  7. using std::endl;
  8. cerr << "text (pointer) = " << static_cast<const void *>(text) << endl;
  9. if (!text) throw std::runtime_error("Is a null pointer really expected?");
  10. cerr << "text (string) = \"" << text << '"' << endl;
  11. return text;
  12. }
  13.  
  14. int main() {
  15. 2_example;
  16. 1_example;
  17. 0_example;
  18. }

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

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

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

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

解决方法

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

我去了一个gcc bug,但它看起来已经被归档并修复了上游:

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

猜你在找的C&C++相关文章