在下面的代码中,getElement
函数提供了几种方法来返回在调用者堆栈上分配的向量元素的值。
NB。我知道可以在v[1]
中使用main
来获得相同的结果,但这仅用于说明目的。
getElement
返回后的vector元素上?std::move
是否合理?以下是代码:
#include <vector>
using namespace std;
class Foo {...};
void getElement(int idx,
vector<Foo> vValue, vector<Foo>& vRef,
Foo& fooRef, Foo* fooPtr)
{
// (vector size checks ommitted for clarity)
// Which of the (exclusive) following instructions allows to
// correctly handle the vector element from the main function?
fooRef = vValue[idx]; //method 1: by reference on a vector copy
&fooPtr = vValue[idx]; //method 2: by pointer on a vector copy
fooRef = vRef[idx]; //method 3: by reference on a vector reference
&fooPtr = vRef[idx]; //method 4: by pointer on a vector reference
}
int main( int argc, char* argv[] ) {
vector<Foo> v { Foo(..), Foo(..), Foo(..) };
Foo fooVal(..);
getElement(1, v, v, fooVal, &fooVal);
// Use fooVal here to handle the vector element
}