-2

I have no idea about what's wrong here.

std::stringstream ss("Title");
ss << " (" << 100 << ")";
const char* window_title = &ss.str().c_str();

I've ran make and it was not happy.

 [17%] Building CXX object CMakeFiles/game.dir/src/main.cpp.o
path: error: cannot take the address of an rvalue of type 'const value_type *'
      (aka 'const char *')
          const char* window_title = &ss.str().c_str();
                                     ^~~~~~~~~~~~~~~~~
1 error generated.
make[2]: *** [CMakeFiles/game.dir/src/main.cpp.o] Error 1
make[1]: *** [CMakeFiles/game.dir/all] Error 2
make: *** [all] Error 2

From what I understand, I'm creating a stringstream with the word "Title" and then appending "(100)" to it. After this, I am retrieving a string, then a "C string", which is a char and storing the pointer to that in window_title.

What's wrong?

Lucien
  • 776
  • 3
  • 12
  • 40

1 Answers1

5

ss.str() returns a temporary object that is destroyed after the call. You shouldn't use pointers to memory of temporary objects, it's undefined behavior. Also, c_str() already returns a pointer to null-terminated char array. Compiler complains that you're trying to not simply use the address to memory of temporary object, but take a pointer to this address, and rightfully so. This way it compiles and works

std::stringstream ss("Title");
ss << " (" << 100 << ")";
//Create a string object to avoid using temporary object
std::string str = ss.str();
const char* window_title = str.c_str();
buld0zzr
  • 962
  • 5
  • 10