2

我有一个简单的功能:

vector<float>& myFunction() {
    //> Do something and return a vector<float> (don't worry about scoping now )
}

现在其他地方的区别是:

vector<float>& myNewVar = myfunction();
             ^

相对

vector<float> myNewVar = myfunction();  //> Without reference

第二个例子不等同于这种情况:

void myFunction(vector<float>& outVector) {
   //> some code
}

vector<float> myVect;
myFunction(myVect);   
4

2 回答 2

4

在这个版本中

vector<float>& myNewVar = myfunction();

myNewVar是对任何返回引用的引用myfunction()

在这一

vector<float> myNewVar = myfunction();

myNewVar是任何 返回引用的副本。myfunction()它将引用作为std::vector<float>的复制构造函数的输入。

也许没有函数可以更好地说明这一点:

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;
于 2013-06-06T09:50:21.297 回答
1

在第二种情况下,调用了一个 copy-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<float>& outVector) {
   //> some code
}

vector<float> myVect;
myFunction(myVect);   

It depends. If you don't assign to outVector inside myFunction, copy-ctor won't be called. Difference is minimal, but it does exist.

于 2013-06-06T09:51:10.637 回答