什么操作符我必须重载,以查看所有操作时传递一个对象到一个函数? [英] What operators do I have to overload to see all operations when passing an object to a function?
本文介绍了什么操作符我必须重载,以查看所有操作时传递一个对象到一个函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想编写一段代码,显示在将对象传递给函数时对对象执行的所有复制/分配/删除等操作。
I would like to write a piece of code that shows all copy/assignment/delete etc. operations that are done on the object when passing it to a function.
我写道:
#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;
}
我忘记了什么吗?
在比较传递对象的不同方式时,还有什么需要考虑的吗?
Did I forget anything? Is there anything else that has to be considered when comparing the different ways of passing an object?
推荐答案
++ 11,您应该添加右值引用:
In C++11, you should add rvalue reference:
A(A&&);
void operator=(A&& a );
这篇关于什么操作符我必须重载,以查看所有操作时传递一个对象到一个函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文