Refference to temp Object


1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>

 void print_me_bad( std::string& s ) {
      std::cout << s << std::endl;
  }

int main()
 {
   print_me_bad( std::string( "World" ) );  // Compile error; temporary object

  return 0;
 }


I know that putting a const keyword in the print_me_bad function would solve the problem.
But my question is , the temporary object string( "World" ) gets destroyed after we passed its closing paranthesys ( right after "Word" literal)?
and that's why we need a const keyword .
Am I correct ?

Thank
Am I correct ?
No. Try this:
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>

 void print_me_bad( std::string& s ) {
      std::cout << s << std::endl;
  }

int main()
 {
     std::string &x = std::string( "Hello" ); // Compiler error: rvalue required
   print_me_bad( std::string( "World" ) );  // Compile error; temporary object

  return 0;
 }
The point is that a non const reference needs a lvalue, but this kind of temporary object is an rvalue.

lvalue: can be used on the left (and right) side of =
rvalue: can be used on the right side of = only
Topic archived. No new replies allowed.