将对象传递给函数时,必须重载哪些运算符才能查看所有操作?
What operators do I have to overload to see all operations when passing an object to a function?
我想编写一段代码来显示将对象传递给函数时对对象执行的所有 copy/assignment/delete 等操作。
我写了这个:
#include <iostream>
class A {
public:
A(){std::cout<<"A()"<<std::endl;}
void operator=(const A& a ){std::cout<<"A=A"<<std::endl;}
A(const A& a){std::cout<<"A(A)"<<std::endl;}
~A(){std::cout<<"~A"<<std::endl;}
};
void pv(A a){std::cout<<"pv(A a)"<<std::endl;}
void pr(A& a){std::cout<<"pr(A& a)"<<std::endl;}
void pp(A* a){std::cout<<"pp(A* a)"<<std::endl;}
void pc(const A& a){std::cout<<"pc(const A& a)"<<std::endl;}
int main() {
std::cout<<" -------- constr"<<std::endl;
A a = A();
std::cout<<" -------- copy constr"<<std::endl;
A b = A(a);
A c = a;
std::cout<<" -------- assignment"<<std::endl;
a = a;
a = b;
std::cout<<" -------- pass by value"<<std::endl;
pv(a);
std::cout<<" -------- pass by reference"<<std::endl;
pr(a);
std::cout<<" -------- pass by pointer"<<std::endl;
pp(&a);
std::cout<<" -------- pass by const reference"<<std::endl;
pc(a);
return 0;
}
我是不是忘记了什么?
在比较传递对象的不同方式时,还有什么必须考虑的吗?
在 C++11 中,您应该添加右值引用:
A(A&&);
void operator=(A&& a );
我想编写一段代码来显示将对象传递给函数时对对象执行的所有 copy/assignment/delete 等操作。
我写了这个:
#include <iostream>
class A {
public:
A(){std::cout<<"A()"<<std::endl;}
void operator=(const A& a ){std::cout<<"A=A"<<std::endl;}
A(const A& a){std::cout<<"A(A)"<<std::endl;}
~A(){std::cout<<"~A"<<std::endl;}
};
void pv(A a){std::cout<<"pv(A a)"<<std::endl;}
void pr(A& a){std::cout<<"pr(A& a)"<<std::endl;}
void pp(A* a){std::cout<<"pp(A* a)"<<std::endl;}
void pc(const A& a){std::cout<<"pc(const A& a)"<<std::endl;}
int main() {
std::cout<<" -------- constr"<<std::endl;
A a = A();
std::cout<<" -------- copy constr"<<std::endl;
A b = A(a);
A c = a;
std::cout<<" -------- assignment"<<std::endl;
a = a;
a = b;
std::cout<<" -------- pass by value"<<std::endl;
pv(a);
std::cout<<" -------- pass by reference"<<std::endl;
pr(a);
std::cout<<" -------- pass by pointer"<<std::endl;
pp(&a);
std::cout<<" -------- pass by const reference"<<std::endl;
pc(a);
return 0;
}
我是不是忘记了什么? 在比较传递对象的不同方式时,还有什么必须考虑的吗?
在 C++11 中,您应该添加右值引用:
A(A&&);
void operator=(A&& a );