c++ - 常量和常量引用参数有什么区别

标签 c++ c++11 constructor constants

我见过很多人将他们的函数参数设置为:

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
----------------

Live Example

如您所见,如果您不通过引用传递,就会生成拷贝。


唯一的区别

void func1(myclass a)

void func2(const myclass a)

是不是第二个例子中的aconst。但是确实没有理由这样做;既然是拷贝,改不改都无所谓。如果你有一个可以使用 const 对象的函数,那么我建议通过 const & 传递以避免复制,只要复制比引用更昂贵(非 pod类型,大于指针的大小)。

关于c++ - 常量和常量引用参数有什么区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36938398/

相关文章:

c++ - 以编程方式退出 MFC 应用程序的正确方法是什么?

c++ - 如何使用 scons 运行 gtest

c++ - move 语义和参数评估顺序

javascript - 如何从父原型(prototype)JS继承权

c++ - 如何将 std::chrono::time_point 转换为 uint64_t?

c++ - 如何编写特征转换以将 'const' 添加到类型*

c++ - 使用非专用模板化类型作为模板参数

c++ - 使用带接口(interface)的 CRTP

Javascript 创建具有 new 和不具有 new + 继承的对象

c# - 为继承的只读字段赋值?