Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does std::pair destroy its dynamically allocated objects?

Tags:

c++

stl

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.

like image 469
ghostinecatnewyear Avatar asked Nov 29 '19 15:11

ghostinecatnewyear


People also ask

Is std :: pair contiguous?

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.

Is std :: string dynamically allocated?

Inside every std::string is a dynamically allocated array of char .

How does C++ reclaim the space that is allocated dynamically to an object?

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.

Is C++ dynamically allocated?

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.


2 Answers

No.

std::vector does not destroy objects whose pointers were added to it by push_back(new T).

Neither does std::pair.

like image 178
user253751 Avatar answered Sep 30 '22 00:09

user253751


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.

like image 23
eerorika Avatar answered Sep 30 '22 01:09

eerorika