C + + vector pointer return value problem

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.