Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

Deleting one member of std::pair

Posted on 2008-10-21
3
Medium Priority
?
1,289 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
3 Comments
 
LVL 31

Accepted Solution

by:
Zoppo earned 336 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 332 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 332 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

Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

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 …
Many modern programming languages support the concept of a property -- a class member that combines characteristics of both a data member and a method.  These are sometimes called "smart fields" because you can add logic that is applied automaticall…
The goal of the tutorial is to teach the user how to use functions in C++. The video will cover how to define functions, how to call functions and how to create functions prototypes. Microsoft Visual C++ 2010 Express will be used as a text editor an…
The viewer will be introduced to the technique of using vectors in C++. The video will cover how to define a vector, store values in the vector and retrieve data from the values stored in the vector.

916 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