For example containers like std::vector<T*>
destroy all of its elements that were addad to it by push_back(new T)
. Does std::pair<T1*, T2*>
does the same when you initialize it like { new T1, new T }
?
I have this question because std::pair
is a structure unlike containers that are classes (it does not mean anything but still). I can not find any information about it.
Edited: despite the fact I thought containers delete
their dynamically allocated elements, this is wrong.
std::pair is a struct, the standard says the compiler determines the layout though the order must be maintained, so in the instance of std::pair<char,char> your compiler may decide to place 3-byte padding after each char for optimal alignment, so no you can't assume contiguous memory layout - end of story.
Inside every std::string is a dynamically allocated array of char .
C++ calls the destructor automatically whenever a variable of a particular class is released. For stack objects, this happens when the function returns. The effect of this rule is that a C++ program that declares its objects as local variables on the stack will automatically reclaim those variables.
C++ allows us to allocate the memory of a variable or an array in run time. This is known as dynamic memory allocation. In other programming languages such as Java and Python, the compiler automatically manages the memories allocated to variables.
No.
std::vector
does not destroy objects whose pointers were added to it by push_back(new T)
.
Neither does std::pair
.
Both vector and pair destroy their elements.
Neither vector nor pair destroy or deallocate objects pointed by their elements.
Some examples:
{
std::vector<int> v {42};
}
Vector allocated dynamically, and deallocated.
{
std::vector<int*> v {new int};
}
Vector allocated dynamically, and deallocated. I allocated dynamically, and leaked the allocation.
{
std::pair<int, int> v {42, 24};
}
No dynamic allocation whatsoever. Great.
{
std::pair<int*, int*> v {new int, new int};
}
I allocated dynamically twice, and leaked both.
{
std::pair<int*, int*> v {new int, new int};
delete v.first;
delete v.second;
}
No leak.... but don't do this. Avoid unnecessary dynamic allocation, and don't use owning bare pointers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With