C++ 使用返回引用的函数将变量声明为引用
我有一个简单的功能:C++ 使用返回引用的函数将变量声明为引用,c++,reference,C++,Reference,我有一个简单的功能: vector<float>& myFunction() { //> Do something and return a vector<float> (don't worry about scoping now ) } int i = 42; // I want a referennce, so I create one int& j = i; // I want a copy, so I make one, eve
vector<float>& myFunction() {
//> Do something and return a vector<float> (don't worry about scoping now )
}
int i = 42;
// I want a referennce, so I create one
int& j = i;
// I want a copy, so I make one, even though j is a reference.
// j is just an alias for i, so k really is a copy of i.
int k = j;
vector&myFunction(){
//>执行一些操作并返回一个向量(现在不必担心作用域)
}
现在在其他地方,这是不同的:
vector<float>& myNewVar = myfunction();
^
vector&myNewVar=myfunction();
^
对
vector<float> myNewVar = myfunction(); //> Without reference
vector myNewVar=myfunction();/>无参考
第二个例子不就是这种情况吗
void myFunction(vector<float>& outVector) {
//> some code
}
vector<float> myVect;
myFunction(myVect);
void myFunction(vector和outVector){
//>一些代码
}
载体myVect;
myFunction(myVect);
在此版本中
vector<float>& myNewVar = myfunction();
myNewVar
是任何myfunction()
返回的引用的副本。它将引用作为std::vector
的复制构造函数的输入
也许在没有函数的情况下可以更好地说明这一点:
vector<float>& myFunction() {
//> Do something and return a vector<float> (don't worry about scoping now )
}
int i = 42;
// I want a referennce, so I create one
int& j = i;
// I want a copy, so I make one, even though j is a reference.
// j is just an alias for i, so k really is a copy of i.
int k = j;
在第二种情况下,将调用复制ctor,在第一种情况下,它不是:
class MyClass
{
public:
MyClass() { }
MyClass(const MyClass & right)
{
printf("Copy ctor\n");
}
};
MyClass & fn()
{
// Only for the sake of example
// Please don't complain ;)
return *(new MyClass());
}
int main(int argc, char * argv)
{
printf("First case\n");
MyClass & a = fn();
printf("Second case\n");
MyClass b = fn();
}
编辑:回答您的问题: 第二个例子不就是这种情况吗:
void myFunction(vector和outVector){
//>一些代码
}
载体myVect;
myFunction(myVect);
视情况而定。如果未在myFunction内赋值给outVector,则不会调用copy ctor。差别很小,但确实存在。第二个是副本,第一个是参考。没关系。mynewvar的类型不是一个引用。是否阅读过?@yes123否,请仔细阅读答案。在第一个例子中,没有复制。是的,但要不复制,我必须声明一个引用,无论函数返回引用还是not@yes123几乎。如果函数不返回引用,您就不能真正返回引用,因为您将把一个引用绑定到一个临时引用,因此会立即得到一个悬空引用。@yes123它一点用处也没有。有时候你真的需要一个推荐人。