我见过很多人将他们的函数参数设置为:
function(const myType &myObj)
Run Code Online (Sandbox Code Playgroud)
我不明白为什么他们使用&后的类型?
似乎const足以阻止构造函数被调用.
所以,我写了下面的代码,我发现结果没有优势.有人可以解释一下吗?
#include <iostream>
using namespace std;
class myclass
{
public:
myclass()
{
cout<<"constructor is called\n";
}
int field;
};
void func1(myclass a)
{
cout<<"func1: "<<a.field<<"\n";
}
void func2(const myclass a)
{
cout<<"func2: "<<a.field<<"\n";
}
void func3(const myclass &a)
{
cout<<"func3: "<<a.field<<"\n";
}
int main ()
{
myclass obj;
obj.field=3;
cout<<"----------------\n";
func1(obj);
cout<<"----------------\n";
func2(obj);
cout<<"----------------\n";
func3(obj);
cout<<"----------------\n";
return 0;
}
Run Code Online (Sandbox Code Playgroud)
结果:
constructor is called
----------------
func1: 3
----------------
func2: 3
----------------
func3: 3
----------------
Run Code Online (Sandbox Code Playgroud)
所以,我写了下面的代码,我发现结果没有优势.有人可以解释一下吗?
问题是你永远不会设置你的拷贝构造函数来输出任何东西来查看是否有副本.如果我们补充
myclass( const myclass & foo) : field(foo.field)
{
cout<<"copy constructor is called\n";
}
Run Code Online (Sandbox Code Playgroud)
输出将是
constructor is called
----------------
copy constructor is called
func1: 3
----------------
copy constructor is called
func2: 3
----------------
func3: 3
----------------
Run Code Online (Sandbox Code Playgroud)
如果您没有通过引用传递,您可以看到副本.
唯一的区别
void func1(myclass a)
Run Code Online (Sandbox Code Playgroud)
和
void func2(const myclass a)
Run Code Online (Sandbox Code Playgroud)
这a是const第二个例子.但是,没有理由这样做; 因为它是一个副本,如果你改变它并不重要.如果你有一个可以使用const对象的函数,那么我建议传递const &以避免复制,只要复制比引用(非pod类型,大于指针大小)更昂贵.