Question

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?

Was it helpful?

Solution

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top