C++: vector implementation and dynamic memory allocation -
I was trying to understand how As I understand, You are right, but you are missing an important point. Because you have a 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 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; }
test
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?
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
Comments
Post a Comment