Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a C++ user-defined literal operator ever be passed a null pointer?

Can a C++ user-defined literal operator ever be passed a null pointer?

This is really happening with an experimental version of g++ (gcc version 4.7.0 20111114 (experimental) [trunk revision 181364] (Debian 20111114-1)) but I am unsure if this is a bug (90% sure) or some strange expected behavior.

Example program:

#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;
}

Output (probably a bug in gcc ... but maybe not?!, hence the question):

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

It's not just "0_example"; it's whenever the literal value is zero. For example, it still happens even when the literal is "0x0000_example".

Is this a bug? Or some strange special-case when the literal's value is zero?

like image 894
wjl Avatar asked Dec 05 '11 00:12

wjl


1 Answers

As Alf P. Steinbach assured me in a nice comment, this is a bug, not standard behavior (no big deal, since I was using a gcc snapshot).

I went to file a gcc bug, but it looks like it's already been filed and fixed upstream:

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

like image 137
wjl Avatar answered Sep 29 '22 00:09

wjl