There are a few things to note about vector as the return value of a function:
1. First, if the vector is a local variable, then it is very dangerous to return a reference to the vector because the associated destructor (~vector ()) is automatically called when the vector is out of scope. If a pointer to a class (ClassName) object is stored in the vector, the related class ClassName destructor is not called and only the associated space is emptied (that is, vector.size () =0), which results in a memory leak. However, if the vector contains objects of class (ClassName), then the related class ClassName destructor is called. So if the vector is a local variable, then it is very dangerous to return the reference to the vector, because the vector has been refactored.
Example:
Write the following code in a function:
Where Testobject and Ptestobject are member variables, this is mostly easy to test
std::vector<ctestobject>testobjectvec; Testobjectvec.push_back (Testobject); Std::vector<ctestobject *> Ptestobjectvec; Ptestobject =new ctestobject (); Ptestobjectvec.push_back (Ptestobject); At the end of the function execution, the Ctestobject destructor is called automatically once, due to the TESTOBJECTVEC//structure, but the Ptestobjectvec destructor does not cause the destructor to be called Ctestobject |
2. When returning a reference, be aware that the function cannot be declared as const or the compilation does not pass
For example:
std::vector& Getvec () const;//statement
Std::vector & Classname1::getvec () const//error
{ 。。。
}
Compile error
Const Std::vector & Getvec () const;//declaration, so that you can, that is, you must return a const reference, only the line, of course, can also be used at both ends const!
2. If it is not a local variable, you can return the reference or the vector iterator (Iterator)
C + + vector pointer return value problem