C++ 复制构造函数给出编译错误 void print\u me\u bad(std::string&s){ std::cout

C++ 复制构造函数给出编译错误 void print\u me\u bad(std::string&s){ std::cout,c++,reference,constants,copy-constructor,temporary,C++,Reference,Constants,Copy Constructor,Temporary,如注释中所述,不能将临时对象绑定到非常量引用 在下列情况下: void print_me_bad( std::string& s ) { std::cout << s << std::endl; } void print_me_good( const std::string& s ) { std::cout << s << std::endl; } std::string hello(

如注释中所述,不能将临时对象绑定到非常量引用

在下列情况下:

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

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

  std::string hello( "Hello" );

  print_me_bad( hello );  // Compiles ok
  print_me_bad( std::string( "World" ) );  // Compile error
  print_me_bad( "!" ); // Compile error; 
  print_me_good( hello ); // Compiles ok

  print_me_good( std::string( "World" ) ); // Compiles ok
  print_me_good( "!" ); // Compiles ok 
创建一个临时std::string对象。首先显式(
std::string(“World”)
),然后通过隐式转换(
“!”
转换为std::string)。这是不允许的

但是,您可以将临时变量绑定到常量引用,这就是为什么其他情况编译得很好的原因:

print_me_bad( std::string( "World" ) );  // Compile error
print_me_bad( "!" ); // Compile error; 

临时对象不能绑定到对非常量的引用。您显示的代码中没有任何复制构造。问题与左值和右值(“临时”对象,基本上)之间的差异以及对常量和非常量对象的引用之间的差异有关。将临时对象绑定到引用(
const
是必需的)-
print_me_good( std::string( "World" ) ); // Compiles ok
print_me_good( "!" ); // Compiles ok