尽管我非常喜欢 C++ 编程,但有一件事我确实不明白。对我来说,最常见的函数编程方式似乎是这样的:
some_function(a variable)
do something according to the data in the variable
example:
bool match_name(const std::string& name)
{
return this->name == name;
}
我发现自己在代码中使用 const ref 来处理 90% 的函数参数(也许我做错了什么)。
我的问题是:为什么变量的副本是参数的“默认”类型?为什么 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
除了历史原因之外,这将产生非常丑陋的影响。这基本上意味着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?
}
并想想穷人&
!除非你提出一种不同的方法来区分引用和非引用,否则你最终会得到
void foo(MyType& myVar) //myVar is a copy?
{
MyType& anotherVar = myVar; // anotherVar is a reference???
}
C++ 有一个完善的对象和对象引用的概念。后者总是通过添加来表示&
输入。你的提议会把事情搞砸,而且 C++ 会比现在更难理解。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)