Managing Scope and Object Lifetime Within STL Vectors

Coming from a C# world, I'm struggling to make sure I don't introduce memory leaks and errors in a C++ project I've been assigned to. I'm writing code that uses structs to parse information from a buffer of data. Because the number of data structures that appear in the buffer can vary at runtime, an stl vector is used to store the processed data. I came across the following block of code in the existing software, and am struggling to understand why it works:

MyVectorOfObjects.clear();
for (unsigned __int8 i = 0; i < NumberOfObjects; i++)
{
    MyParserObject parserObject;                // Declaring without 'new'?
    parserObject.Decode(buffer, offset, size);  // A method on the struct.
    MyVectorOfObjects.push_back(parserObject);  // Does this keep parserObject in scope?
}

My questions are specifically:

  • According to this question, wouldn't parserObject go out of scope each iteration since the new keyword isn't used? Evidently this code has been working.

  • In this case, does placing the object in a vector keep the parserObject in scope?

  • According to this question, the parserObject is copied. If this is the case, what are the performance implications (eg memory consumption, memory allocation, etc.) of this? Also, do the copied parserObjects then assume the same scope as the vector?

  • Thanks for any help.


  • Yes, the instance of parserObject that is declared within the for loop goes out of scope each time the loop iterates.

  • No, placing the parserObject into the vector doesn't keep that object in scope. The push_back() method will make a copy of that object that is now owned by the vector . You need to make sure your objects can be properly copied (copy-constructor and assignment operator may be necessary). Copies contained in the vector in this example are owned by the vector, and will have object lifetimes that are similar to the vector itself.

  • The paserObject is copied, and this may have implications on memory usage and performance. If the parserObject is not trivial to copy then this can be an expensive operation. This is wholly dependent upon your implementation of the parserObject .


  • MyVectorOfObjects.push_back(parserObject);  // Does this keep parserObject in scope?
    

    push_back makes a copy of the object and stores it.

    So make sure that you've defined copy-constructor (and copy-assignment) properly for the class MyParserObject if it has pointer member(s). Or else default code generated by the compiler would be enough, provided each member of MyParserObject follows the same pattern (ie they've defined the copy-constructor (and copy-assignment) properly if they've pointer members, or else default-code generated by the compiler would be enough, provided .... and so on.)

    链接地址: http://www.djcxy.com/p/96544.html

    上一篇: 检测堆栈或堆分配

    下一篇: 管理STL向量中的范围和对象生命周期