-1

Explain, please, me next things.

#include <iostream>
#include <set>

int main() {
    std::set<int>* a = new std::set<int>;

    a->insert(2);
    a->insert(5);

    for ( std::set<int>::iterator it = a->begin(); it != a->end(); it++ ) {
        std::cout << *it << std::endl;
    }

    std::cout << "Deleting a....." << std::endl;

    delete a;

    for ( std::set<int>::iterator it = a->begin(); it != a->end(); it++ ) {
        std::cout << *it << std::endl;
    }


    return 0;
}

$ g++ test6.cpp && a
2
5
Deleting a.....
2
5
3544585
  1. Does it make any sense to use operator new creating std::set? As I read in manuals, std::set has its own Allocator object, which is responsible for dynamic memory allocating using operator new. But interesting to know experienced members point of view.
  2. Why after deallocating memory using delete a members of std::set are still avaliable and have values 2 and 5 like before delete a. And what is the right way to delete member a. Thanks.
Aaron McDaid
  • 26,501
  • 9
  • 66
  • 88
yozhik
  • 29
  • 1
  • 3

2 Answers2

2

Watch this part of Stroudstrup's talk at Going Native 2013

1) No, you can just create a local variable a and let it be released at the end of the function through normal control flow

std::set<int> a;
a.insert(2);
a.insert(5);

2) You're getting lucky. It's undefined behavior to access memory that has been released. Run this code through valgrind and you'll see errors.

int *ip = new int{1};
delete ip;
int a = *ip; // NOT SAFE, maybe 1, maybe 24630751, maybe crash
Ryan Haining
  • 35,360
  • 15
  • 114
  • 174
1

No, the standard library has memory management functionality included, so the programmer does not have to concern themselves with this.

The reason you are still seeing sensible values output after the delete, is because your PC has not written new values over the memory spaces yet. This is why attempting to access memory after it is deleted is under the "undefined behavior" umbrella.

Lawrence Aiello
  • 4,560
  • 5
  • 21
  • 35