I just noticed in my code that I declared a vector on the stack (instead of the heap) and then used my “set”-function to set the member variable of another class to this vector. The only problem is that after exiting my function (myFunction) the vector should be destroyed (because it is on the stack) and the reference to this vector should point to “nothing meaningful”. But my code is working correctly and so I was asking myself why. Am I just lucky because the portion of the memory where the vector was, is existing because nobody deleted it until now? So it is a matter of luck if my code is not crashing?
Here is the code:
void myFunction() {
std::vector<std::vector<double>> vDoubleVector = MyUtils::CreateDoubleVector(); //Creates a
double vector (but not on heap)
MyClass mC;
mC.SetDoubleVector(vDoubleVector);
}
class MyClass {
std::vector<std::vector<double>> mDoubleVector;
void SetDoubleVector(std::vector<std::vector<double>>& aDoubleVector) {
mDoubleVector = aDoubleVector;
}
}
Since Luchian was faster than me, I’m going to add sensible improvement to this code:
Citing “rule of thumb” – If you need to copy, do it in the interface.
//EDIT to make the answer complete.
Your code did copy the vector by use of its
operator=inSetDoubleVector.