Solved

Deleting one member of std::pair

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

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Suggested Solutions

Introduction This article is a continuation of the C/C++ Visual Studio Express debugger series. Part 1 provided a quick start guide in using the debugger. Part 2 focused on additional topics in breakpoints. As your assignments become a little more …
Container Orchestration platforms empower organizations to scale their apps at an exceptional rate. This is the reason numerous innovation-driven companies are moving apps to an appropriated datacenter wide platform that empowers them to scale at a …
The goal of the video will be to teach the user the concept of local variables and scope. An example of a locally defined variable will be given as well as an explanation of what scope is in C++. The local variable and concept of scope will be relat…
The goal of the video will be to teach the user the difference and consequence of passing data by value vs passing data by reference in C++. An example of passing data by value as well as an example of passing data by reference will be be given. Bot…

820 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