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
parserObjectgo out of scope each iteration since thenewkeyword isn’t used? Evidently this code has been working. -
In this case, does placing the object in a
vectorkeep theparserObjectin scope? -
According to this question, the parserObject is copied. If this is the case, what are the performance implications (e.g. 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
parserObjectthat is declared within theforloop goes out of scope each time the loop iterates.No, placing the
parserObjectinto thevectordoesn’t keep that object in scope. Thepush_back()method will make a copy of that object that is now owned by thevector. 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 thevectoritself.The
paserObjectis copied, and this may have implications on memory usage and performance. If theparserObjectis not trivial to copy then this can be an expensive operation. This is wholly dependent upon your implementation of theparserObject.