Destructors in STL?

This is a discussion on Destructors in STL? within the C++ Programming forums, part of the General Programming Boards category; Hi I see that all stl components have destructors. string s; s.~string(); But i know that we don't need to ...

  1. #1
    Registered User
    Join Date
    Jan 2006
    Posts
    61

    Destructors in STL?

    Hi
    I see that all stl components have destructors.
    string s;
    s.~string();

    But i know that we don't need to delete stl componenets.I read all stl components automatically delete themself.Is this wrong?

    If true what is the function of destructors in STL?

    Thanks...

  2. #2
    Registered User
    Join Date
    May 2006
    Posts
    903
    You should never call a destructor, it will call itself automatically. I can't think of a good example where you'd need to call a destructor manually. What you heard is most probably that STL containers allocate and deallocate memory automatically and not that the objects themselves are deallocated automatically (which they are, anyway).

    Edit: FYI, any class/structure has a destructor.

  3. #3
    Registered User whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    7,692
    When an object falls out of scope or gets deleted, it's destructor is called. It's the same for STL containers. the destructor does all the cleaup; that's what it's purpose is.

  4. #4
    Super Moderator VirtualAce's Avatar
    Join Date
    Aug 2001
    Posts
    9,596
    Try and allocate 100 objects on the heap and stick them in a vector. At shutdown, simply call vector.clear() and watch what happens.
    Last edited by VirtualAce; 08-09-2006 at 05:58 AM.

  5. #5
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,796
    >I can't think of a good example where you'd need to call a destructor manually.
    The only time I can think of would be in conjunction with placement new, but that's a very rare and specific situation.

    >I read all stl components automatically delete themself.
    Yes, the destructor is called automatically when the lifetime of an object ends.
    My best code is written with the delete key.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. C Formatting Using STL
    By ChadJohnson in forum C++ Programming
    Replies: 4
    Last Post: 11-18-2004, 04:52 PM
  2. im extreamly new help
    By rigo305 in forum C++ Programming
    Replies: 27
    Last Post: 04-23-2004, 11:22 PM
  3. STL or no STL
    By codec in forum C++ Programming
    Replies: 7
    Last Post: 04-12-2004, 02:36 PM
  4. Prime Number Generator... Help !?!!
    By Halo in forum C++ Programming
    Replies: 9
    Last Post: 10-20-2003, 07:26 PM
  5. include question
    By Wanted420 in forum C++ Programming
    Replies: 8
    Last Post: 10-17-2003, 03:49 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21