为什么要将对象的副本作为函数的参数?为什么 const ref 不是参数的默认方式?

gro*_*190 3 c++ pass-by-reference pass-by-value

尽管我很喜欢 C++ 编程,但有一件事我真的不明白。对我来说,最常见的函数编程方式似乎是这样的:

some_function(a variable)
    do something according to the data in the variable
Run Code Online (Sandbox Code Playgroud)

例子:

bool match_name(const std::string& name)
{
    return this->name == name;
}
Run Code Online (Sandbox Code Playgroud)

我发现自己对代码中 90% 的所有函数参数都使用了 const ref(也许我做错了什么)。

我的问题是:为什么变量的副本是“默认”类型的参数?为什么 const ref 不是默认值?

为什么不是这样的?:

void my_function(My_type object)      // <- const ref

void my_function(ref My_type object)  // <- ref (mutable)

void my_function(copy My_type object) // <- copy
Run Code Online (Sandbox Code Playgroud)

Yks*_*nen 5

除了历史原因,这将产生非常丑陋的影响。它基本上意味着MyType myVarName当是函数范围或在函数参数列表中使用时会有不同的含义。

void foo(MyType myVar) //myVar is const ref
{
    MyType anotherVar = myVar; // anotherVar is a copy, what?
    const MyType& myVarRef = myVar; //a reference, but it looks like it has different type than myVar?
}
Run Code Online (Sandbox Code Playgroud)

想想穷人&!除非你提出一种不同的方式来区分 refs 和 non-refs,否则你最终会得到

void foo(MyType& myVar) //myVar is a copy?
{
    MyType& anotherVar = myVar; // anotherVar is a reference???
}
Run Code Online (Sandbox Code Playgroud)

C++ 有一个完善的对象概念和对对象的引用。后者总是通过添加&到类型来表示。你的提议会把它搞砸,C++ 会比它更难理解。