Can anyone with a deeper understanding of the C ++ standard than me, comment on this?
This is my sample program.
#include <string>
#include <iostream>
int main(int argc, char* argv[]) {
const std::string message("hello world");
std::cout << std::hex << (void*)message.c_str() << std::endl;
const std::string& toPrint = (argc > 0) ? message : "";
std::cout << std::hex << (void*)toPrint.c_str() << std::endl;
return 0;
}
On one machine, he does this:
g++ (Debian 4.7.2-5) 4.7.2
Copyright (C) 2012 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
0x9851014
0x9851014
messageand toPrintseem to refer to the same instance that I would expect. However, on another machine, this happens:
g++ (Ubuntu 5.2.1-22ubuntu2) 5.2.1 20151010
Copyright (C) 2015 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
0x7ffeb9ab4ac0
0x7ffeb9ab4ae0
Here, it looks like the compiler built a copy messagefor toPrintto point to.
Which behavior is correct according to the C ++ standard? Or is it generally undefined?
source
share