deallocating newly created static classes

This is a discussion on deallocating newly created static classes within the C++ Programming forums, part of the General Programming Boards category; Hello, I have a while loop, and in it, I allocates a new class called TokenItem. It is then pushed ...

  1. #1
    Registered User
    Join Date
    Jul 2011
    Posts
    27

    deallocating newly created static classes

    Hello,
    I have a while loop, and in it, I allocates a new class called TokenItem. It is then pushed into a vector. Question: When is the TokenItem deallocated? Do I have to explicitly delete it?

    Code:
    while (string::npos != pos || string::npos != lastPos)    {        // Found a token, add it to the vector.    
    	char tokenStateInsert;
    	if (tokenState==TOKEN_OFF) 
    		tokenStateInsert=' ';
    	else tokenStateInsert= str.at(pos+1);
    
    	tokens.push_back( TokenItem(tokenStateInsert,   
    		                str.substr(lastPos, pos - lastPos)));        // Skip delimiters.  Note the "not_of"        
    	
    	lastPos = str.find_first_not_of(delimiters, pos);        // Find next "non-delimiter"     
    	pos = str.find_first_of(delimiters, lastPos);   
    } //while

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    22,304
    When the vector is destroyed, the token objects it stored will be destroyed.
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    Registered User
    Join Date
    Jul 2011
    Posts
    27
    Also is it true that as long as I don't create classes using new and a pointer then I don't have to worry about memory leaks and deallocation? Is this called static allocation?

    What's the best way to detect memory leaks?

  4. #4
    Registered User
    Join Date
    Jun 2005
    Posts
    6,670
    Quote Originally Posted by derder View Post
    Also is it true that as long as I don't create classes using new and a pointer then I don't have to worry about memory leaks and deallocation?
    That question is imprecise.

    The short answer is "no". There are many ways to cause memory leaks without "using new and a pointer".

    The key is, if you have any code that relies on dynamic allocation (or memory, or any other resource) that every bit of code contributes to managing it correctly. So, if a constructor allocates memory, it is necessary that all constructors and assignment operators manage dynamic resources in a consistent manner, and that the destructor correctly deallocate.

    If your class makes use of another class that does not correctly manage memory allocation and deallocation, then your class will also exhibit problems associated with memory leaks, dangling references, etec.
    Quote Originally Posted by derder View Post
    Is this called static allocation?
    No it is not.

    Static memory allocation refers to a process of allocating memory at compile time BEFORE a program is executed.

    Quote Originally Posted by derder View Post
    What's the best way to detect memory leaks?
    Define best.

    The recommended technique is to do everything you can prevent memory leaks occurring in the first place, rather than trying to find them once they exist.

    Preventing memory leaks is not easy. However, detecting them if they exist is much harder (except in programs that are small/trivial).
    Right 98% of the time, and don't care about the other 3%.

    If I seem grumpy or unhelpful in reply to you, or tell you you need to demonstrate more effort before you can expect help, it is likely you deserve it. Suck it up, Sunshine, and read this, this, and this before posting again.

  5. #5
    Registered User
    Join Date
    Jul 2011
    Posts
    27
    What is the difference between
    Code:
    TokenItem *tok = new TokenItem(); delete tok;
    and
    Code:
    TokenItem tok = TokenItem();
    In the later example, I suppose there is some sort of mechanism to track the reference and allow it to garbage collect. As long as I don't use the new and delete allocator, then the garbage collector takes care of things for me. This same goes if I decalre string str="abc", and create substrings, etc.

    By the word 'best', I meant is there a simple Visual Studio Debugger that start the program and ends it, you can can find out how much heap was created and left.

  6. #6
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    22,304
    Quote Originally Posted by derder
    In the later example, I suppose there is some sort of mechanism to track the reference and allow it to garbage collect.
    Unless you specially make use of a garbage collector, there is no garbage collection involved. In your latter example, tok is a variable of object type, not of reference type*, so there is no notion of "track the reference".

    In C++, there is the idiom of RAII: Resource Acquisition Is Initialisation. Basically, the idea is to tie the lifetime of a resource with the lifetime of an object. As such, if the object is destroyed, e.g., because it is a local variable that goes out of scope, the resource will be released, without the need to explicitly release it.

    * I use "reference type" here as a computer science concept, i.e., not only to mean a C++ reference type or a pointer type, but also reference types from languages such as C# and Java, which use similiar syntax as in your example but in which the variable is actually of reference, not object, type, and which behave as pointers without pointer syntax.

    Also, note that we would generally simplify this:
    Code:
    TokenItem tok = TokenItem();
    to:
    Code:
    TokenItem tok;
    In practice there would be no difference because the copying of the unnamed temporary TokenItem object would be elided by the compiler.
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  7. #7
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Posts
    23,027
    C++ has no garbage collector*. Anything that isn't allocated with new (or some external API function from APIs such as DirectX or Win32 API) is placed on the stack. And once the current scope ends, all the variables placed inside that scope on the stack are destroyed.

    If we combine this by wrapping pointers allocated with new inside such an object allocated on the stack, we can manage memory by having it released when the object goes out of scope. This idiom is called RAII as laserlight points out. For more info, you may want to check out smart pointers.

    *) That is, there is no official garbage collector, but there are 3rd parties.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  8. #8
    Registered User
    Join Date
    Apr 2006
    Posts
    2,053
    Quote Originally Posted by derder View Post
    Also is it true that as long as I don't create classes using new and a pointer then I don't have to worry about memory leaks and deallocation? Is this called static allocation?

    What's the best way to detect memory leaks?
    Quote Originally Posted by derder View Post
    What is the difference between
    Code:
    TokenItem *tok = new TokenItem(); delete tok;
    and
    Code:
    TokenItem tok = TokenItem();
    In the later example, I suppose there is some sort of mechanism to track the reference and allow it to garbage collect. As long as I don't use the new and delete allocator, then the garbage collector takes care of things for me. This same goes if I decalre string str="abc", and create substrings, etc.
    It is true, that any object that is created on the stack or any static or global variables, created without new (or C's malloc and calloc functions), does not require an explicit release. So, yes, there is no way to leak such an object. And this is one reason why stack variables are generally preferable to dynamic allocation. However, there are other considerations. If you ever want to create an object, in one place and use it in another, without making a copy, stack or "automatic" variables are unsuitable. An additional considerations is that your program has a much smaller limit on stack space than it has on dynamic memory. So dynamic memory is used a lot.

    However, there are ways to make it easy to manage dynamic memory so that you don't have to worry about memory leaks (as long as you do it right).

    One way dynamic memory is used, is that an object might use some dynamic memory to supplement it's state. In this case the formula is strait forward. The constructor allocates the memory needed; the copy constructor and assignment operator copy an object, allocating new memory, and in the case of the assignment operator releasing the old memory; and the destructor releases the memory. In this way, the task of managing memory is contained withing the object, and is where it is expected. No memory management is needed by anyone other than the writer of the class.

    Another way to make the same tax easy is to use smart pointers. Smart pointers are automatic variables that will manage your dynamic memory for you. They're automatic variables, so they will themselves be destroyed when they go out of scope, but when they are copied they will appropriately manage the copying of the memory you make them manage, depending on the contract of the particular smart pointer you use. This means you never have to call delete or worry about leaks, as long as you abide by the contract of the smart pointer, by only referring to the pointed to object through the pointer. Note that this does not solve problems with managing objects across multiple threads.

    And a third way, though more rare, is to get a garbage collector for C++.
    It is too clear and so it is hard to see.
    A dunce once searched for fire with a lighted lantern.
    Had he known what fire was,
    He could have cooked his rice much sooner.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. C++.NET, static classes
    By Magos in forum C++ Programming
    Replies: 1
    Last Post: 08-13-2008, 06:08 PM
  2. static classes vs objects
    By earnshaw in forum C# Programming
    Replies: 5
    Last Post: 02-08-2006, 03:19 PM
  3. assigning to static map<>s in classes
    By drrngrvy in forum C++ Programming
    Replies: 6
    Last Post: 10-18-2005, 10:05 PM
  4. static in classes
    By hebele in forum C++ Programming
    Replies: 2
    Last Post: 04-08-2005, 01:34 PM

Tags for this Thread


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