Solved

Deleting one member of std::pair

Posted on 2008-10-21
3
1,213 Views
Last Modified: 2011-04-14
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");      
      pair->second.~string();
0
Comment
Question by:chsalvia
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
3 Comments
 
LVL 31

Accepted Solution

by:
Zoppo earned 84 total points
ID: 22765638
Hi chsalvia,

I don't think that's a good idea, since as soon as the '*pair' is deleted IMO the ~string() will be called anew for 'pair->second'. This might be ok for strings, but for other objects maybe not.

Why don't you simply empty the string?

ZOPPO
0
 
LVL 53

Assisted Solution

by:Infinity08
Infinity08 earned 83 total points
ID: 22765668
The placement new was done for the pair, not for the string in it. As Zoppo said, the string will be cleaned up when the pair is cleaned up, and the pair will be cleaned up when you explicitly call its destructor.

The below code illustrates this. The (commented) output you get is :

        Allocating memory ...
        Placement new ...
        Test::Test()                                <--- construction of the temporary object
        Test::Test(test)                          <--- copy construction (the copy is placed in the pair)
        Test::~Test()                              <--- destruction of the temporary object
        Cleaning up ...
        Test::~Test()                              <--- destruction of the copy inside the pair as soon as the pair destructor is called explicitly
        All done !
#include <iostream>
#include <utility>
 
class Test {
  public :
    Test() {
      std::cout << "Test::Test()" << std::endl;
    }
    Test(const Test &test) {
      std::cout << "Test::Test(test)" << std::endl;
    }
    ~Test() {
      std::cout << "Test::~Test()" << std::endl;
    }
};
 
int main(void) {
  std::cout << "Allocating memory ..." << std::endl;
  void* buf = std::malloc(sizeof(std::pair<int, Test>));
 
  std::cout << "Placement new ..." << std::endl;
  std::pair<int, Test>* pair = new (buf) std::pair<int, Test>(555, Test());      
 
  std::cout << "Cleaning up ..." << std::endl;
  pair->std::~pair<int, Test>();
 
  std::cout << "All done !" << std::endl;
 
  return 0;
}

Open in new window

0
 
LVL 39

Assisted Solution

by:itsmeandnobodyelse
itsmeandnobodyelse earned 83 total points
ID: 22766249
To add to above comments:

The std::pair has a trivial destructor cause it has data members and not pointers for the template argument objects:

template<class _Ty1,
      class _Ty2> struct pair
{      // store a pair of values
     ...
     _Ty1 first;      // the first stored value
     _Ty2 second;      // the second stored value
};

If you call the destruktor of the second member explicitly, the member turns invalid and most probably it would crash if you later access the string element. It surely would crash if you would delete the pair object. But it should work ok - though I don't see much value in it -  if you only free the buf pointer as no destructor was called and you already hvae called the destructor of the string.
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

  Included as part of the C++ Standard Template Library (STL) is a collection of generic containers. Each of these containers serves a different purpose and has different pros and cons. It is often difficult to decide which container to use and …
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
The viewer will learn how to pass data into a function in C++. This is one step further in using functions. Instead of only printing text onto the console, the function will be able to perform calculations with argumentents given by the user.
The viewer will learn how to use the return statement in functions in C++. The video will also teach the user how to pass data to a function and have the function return data back for further processing.

751 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question