c++ - 为什么这里不调用复制构造函数

标签 c++

stri(){}

stri(char *s);//constructor used to initilize object with constant string

stri(stri &s1);//copy constructor performs memberwise copy

friend stri operator+(stri &s1,stri &s2);//conccats two string objects

void operator=(stri &s);//performs memberwise copy

//In main
//s1 and s2 are initilized with constant strings
stri s3=s1+s2; //Gives error? However when copy constructor is removed works fine

最佳答案

你这样声明复制构造函数:

stri(stri &s1);

这一行,特别是 = 右边的表达式,产生了一个临时的:

stri s3 = s1+s2;
       // ^^^^^ the result of this expression is a temporary

因为这是拷贝初始化,所以需要调用拷贝构造函数。但是由于临时对象无法绑定(bind)到对非常量对象的引用,因此会出现错误。

当您注释掉复制构造函数时,编译器会为您生成一个。那么它的签名就是

stri(stri const&);

现在它需要一个对 const 的引用,一个临时变量可以绑定(bind)到它。修复现在应该很明显了。

请注意,即使格式良好的复制初始化需要可访问的复制构造函数,编译器也可以选择在优化期间省略对它的调用,即使该省略改变了程序的可观察行为。

关于c++ - 为什么这里不调用复制构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16835913/

相关文章:

c# - 在 C# WPF 应用程序中使用 C++11 库有哪些选择?

python - 通过 sh 导入模块错误运行 .py 脚本

c++ - 使用其中包含 goto 和标签的宏展开循环

c++ - 为什么在 Windows/unix/linux 中使用管道被认为是危险的?

C++:value_type 与 make_pair,哪个更快用于 map 插入?

c++ - 将管道与字符串数组一起使用

c++ - 如何在没有 float / double 的情况下生成均匀分布和高斯分布的伪随机数?

c++ - 是否需要动态分配单个 int ?

c++ - CMake工具链文件: Appropriate value of `CMAKE_SYSTEM_PROCESSOR` for embedded development

c++ - LUA 和 C++ : How to properly use C++ function inside LUA's code