Solved

Deleting one member of std::pair

Posted on 2008-10-21
3
1,158 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 30

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

Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

Join & Write a Comment

Article by: SunnyDark
This article's goal is to present you with an easy to use XML wrapper for C++ and also present some interesting techniques that you might use with MS C++. The reason I built this class is to ease the pain of using XML files with C++, since there is…
C++ Properties One feature missing from standard C++ that you will find in many other Object Oriented Programming languages is something called a Property (http://www.experts-exchange.com/Programming/Languages/CPP/A_3912-Object-Properties-in-C.ht…
The viewer will learn how to user default arguments when defining functions. This method of defining functions will be contrasted with the non-default-argument of defining functions.
The viewer will be introduced to the member functions push_back and pop_back of the vector class. The video will teach the difference between the two as well as how to use each one along with its functionality.

747 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

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now