Deleting one member of std::pair
Posted on 2008-10-21
Suppose you have an std::pair where either T1 or T2 in the pair have non-trivial constructors. If such a pair object is instantiated using placement new, is it safe to manually deallocate either T1 or T2 of the pair (whichever has the non-trivial constructor), by calling the destructor on it manually?
For example, suppose we have a pair type std::pair<int, string>, and we instantiate it using placement new. Then we set the pair.second (the string) to some value. Then we call the destructor of pair.second. Is this an operation that results in defined behavior?
The following example code works fine on my machine, but I wonder if it is safe.
void* buf = std::malloc(sizeof(std::pair<int, string>));
std::pair<int, string>* pair = new (buf) std::pair<int, string>(555, "Hello World");