Simple Return By Reference Example
Shouldn't this return the same vector and the outputs be equal??
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
|
#include <iostream>
#include <string>
#include <stdio.h>
#include <stdlib.h>
#include <vector>
void printVector(const std::vector<float>& vec) {
std::cout << "located at: " << &vec[0] << std::endl;
for(int i = 0; i < vec.size(); i++) {
std::cout << i << ": " << vec[i] << std::endl;
}
}
std::vector<float>& rVec(std::vector<float>& myVec) {
return myVec;
}
int main(int argc, char* argv[]) {
std::vector<float> myVec(4,1);
std::vector<float> secondVec = rVec(myVec);
myVec[0] = 3;
printf("myVec\n");
printVector(myVec);
printf("secondVec\n");
printVector(secondVec);
return 0;
}
|
Output:
myVec
located at: 0x604010
0: 3
1: 1
2: 1
3: 1
secondVec
located at: 0x604030
0: 1
1: 1
2: 1
3: 1
|
Thanks!
Is secondVec meant to be a reference?
std::vector<float>& secondVec = rVec(myVec);
secondVec is not a reference.
ooooh, yes just looked up return by reference again. Totally missed that. Thanks for the quick response!
Topic archived. No new replies allowed.