我见过很多人将他们的函数参数设置为:
function(const myType &myObj)
我不明白为什么他们在类型后面使用&
?
似乎 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;
}
结果:
constructor is called
----------------
func1: 3
----------------
func2: 3
----------------
func3: 3
----------------
最佳答案
So, I wrote the following code and I see no advantage in the result. Can someone explain that?
问题是您从未将复制构造函数设置为输出任何内容以查看是否创建了拷贝。如果我们添加
myclass( const myclass & foo) : field(foo.field)
{
cout<<"copy constructor is called\n";
}
输出将是
constructor is called
----------------
copy constructor is called
func1: 3
----------------
copy constructor is called
func2: 3
----------------
func3: 3
----------------
如您所见,如果您不通过引用传递,就会生成拷贝。
唯一的区别
void func1(myclass a)
和
void func2(const myclass a)
是不是第二个例子中的a
是const
。但是确实没有理由这样做;既然是拷贝,改不改都无所谓。如果你有一个可以使用 const
对象的函数,那么我建议通过 const &
传递以避免复制,只要复制比引用更昂贵(非 pod类型,大于指针的大小)。
关于c++ - 常量和常量引用参数有什么区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36938398/