应避免调用复制构造函数的两种情况



我已经了解了关于调用复制构造函数的三种情况

1.正在从同一类的对象初始化变量

2.使用类的值参数调用函数

3.函数返回的值是类的对象

教科书上还说,对于以上两种情况(案例2和3(,为了避免调用复制构造函数,请使用引用调用

我搜索了一些信息,但我不能完全理解。

例如(我自己做代码(

class CpClass{
int p;
CpClass(const CpClass &obj){
cout<<"user-defined constructor"<<endl;
p = obj.p; 
}
~CpClass(){
cout<<"destructor"<<endl;
}
};
void show1(String &s)
{ cout << "show1 : " << s.p; }
void show2(String s)
{ cout << "show2 : " << s.p; }
int main(){
CpClass c1(10);
CpClass c2(c1);
show1(c2);
show2(c2);
};

我找到了一些关于这个的信息。

第一个,当我们传递一个类对象的参数时,如果该参数是引用形式而不是值,那么它不会在函数结束后立即调用析构函数。当主函数结束时,它调用析构函数

第二个,它在复制参数时调用构造函数,无论参数形式是通过值调用还是通过引用调用(在代码中,String&s或Strings(

我说得对不对?

由于您发布的代码没有编译,我将其更改为:

#include <iostream>
using namespace std;
struct CpClass{
int p;
CpClass(int i){
cout<<"user-defined constructor"<<endl;
p = i; 
}
CpClass(const CpClass &obj){
cout<<"user-defined constructor"<<endl;
p = obj.p; 
}
~CpClass(){
cout<<"destructor"<<endl;
}
};
void show1(CpClass &s)
{ cout << "show1 : " << s.p; }
void show2(CpClass s) { // Constructor
cout << "show2 : " << s.p; 
} // Destructor for s
int main() {
CpClass c1(10); // Constructor
CpClass c2(c1); // Constructor
show1(c2);
show2(c2);
return 0;
}; // Desctructor for c2, c1

以下行调用构造函数

CpClass c1(10);
CpClass c2(c1);
show2(c2);

第一个解构造器在离开函数后被调用

void show2(CpClass s)

在离开main函数(按此顺序(时调用c2c1的析构函数

CpClass &sCpClass * const s的句法糖。这意味着s包含对象的地址,而不是副本。语法糖意味着这是一个简短的形式,你不需要取消引用。

相关内容

最新更新