C++: vector implementation and dynamic memory allocation -


I was trying to understand how vector is implemented in C ++ It was asked, and so I looked at it, and I have a small question that it is right to believe the implementation in the connected question, we see this code:

  int main () {Vector & lt; Int & gt; Test2 = test_Vector (); Cout & lt; & Lt; Test 2 [0] & lt; & Lt; Endl; Return 0; } // Below is not a STL vector object, but one of the related questions, // where the STL vector asking which attempts to apply itself / vector & lt; Int & gt; Test_Vector () {Vector & lt; Int & gt; testing; Test.push_back (5); Return examination; }   

As I understand, test object is created locally, so when test_vector The method returns, the local object exits from the scope, causing the destructor to be called and delete - dials the dynamic array. Since the code actually works and 5 prints, I think I am wrong, what is the correct explanation?

You are right, but you are missing an important point.

Because you have a vector & lt; Int & gt; Returning , you should think of it as a copy, it usually calls the copy constructor, which is test to the vector & lt; Int & gt; Copy in a new example of . The copy creator has been implemented in the linked question:

  template & lt; Class T & gt; Vector & lt; T & gt; :: Vector (Cunt Vector & lt; T & gt; & amp; v) {my_size = v.my_size; My_capacity = v.my_capacity; Buffer = new t [my_size]; For (Int I = 0; i   

Note that copy-constructor can not be used due to return value optimization (see child-splitting in the comments below) In many cases, the compilers should remove the copy Is allowed, and the C ++ standard allows for the fact that this optimization can change program behavior .

The object is copied, or RVO is applied, you should end up with the same thing. Optimization should not ruin your object by following object-oriented practices.

You should always think about the function return value that the value ( i.e. copied) and then consider that your compiler is probably doing RVO is not important to forget

Comments

Popular posts from this blog

excel vba - How to delete Solver(SOLVER.XLAM) code -

github - Teamcity & Git - PR merge builds - anyway to get HEAD commit hash? -

ios - Replace text in UITextView run slowly -