【发布时间】:2016-12-23 16:54:27
【问题描述】:
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
在上面的复制构造函数程序中,为什么我在传递“世界”时会出现第二种情况的编译错误?
【问题讨论】:
-
临时不能绑定到非常量的引用。
-
您显示的代码中的任何地方都没有复制构造。问题与左值和右值(基本上是“临时”对象)之间的差异以及对常量和非常量对象的引用之间的差异有关。
-
将临时对象绑定到引用(需要
const)-herbsutter.com/2008/01/01/…
标签: c++ reference constants copy-constructor temporary