How to free static member variable in C++? - c++

Can anybody explain how to free memory of a static member Variable? In my understanding it can only be freed if all the instances of the class are destroyed. I am a little bit helpless at this point...
Some Code to explain it:
class ball
{
private:
static SDL_Surface *ball_image;
};
//FIXME: how to free static Variable?
SDL_Surface* ball::ball_image = SDL_LoadBMP("ball.bmp");

The pointer itself will be around until the program shuts down. However, what it points to is fair game. You can free that at any time.
If what you're worried about is memory leaks, then you have a few options that I see:
Just let it leak. All the memory from the program will be released when it shuts down. However, if you need more than just the memory being freed (like you want a destructor to run), then that's not such a good idea.
Have a static member variable which keeps track of how many instances of the class have been created. Free the memory when it reaches zero and reallocate it if it goes above 0 again.
Have a function of some kind which runs when the program is shutting down and have it worry about freeing the memory.
If you can, make it so that it's not a pointer anymore. If it's not a pointer, you don't have to worry about it.
Use a smart pointer or auto_ptr. That way, when the pointer itself is destroyed, the memory will be taken care of.
Personally, I'd advise 4 if you can and 5 if you can't, but you have several options.

From the sound of it, you don't really want a pointer at all. In fact, since this is coming from a factory function in a C library, it isn't really a "first-class" C++ pointer. For example, you can't safely delete it.
The real problem (if there is one) is to call SDL_FreeSurface on it before the program exits.
This requires a simple wrapper class.
struct smart_sdl_surface {
SDL_Surface *handle;
explicit smart_sdl_surface( char const *name )
: handle( SDL_LoadBMP( name ) ) {}
~smart_sdl_surface()
{ SDL_FreeSurface( handle ); }
};
class ball
{
private:
static smart_sdl_surface ball_image_wrapper;
static SDL_Surface *& ball_image; // reference to the ptr inside wrapper
};
smart_sdl_surface ball::ball_image_wrapper( "ball.bmp" );
SDL_Surface *&ball::ball_image = ball::ball_image_wrapper.handle;
When the program initializes, the constructor is called and the file is read. When the program exits, the destructor is called and the object is destroyed.

The static member variable in this case is a pointer. You can't free it, but you can free what it points to:
SDL_FreeSurface(ball_image);
You might then want to set ball_image to 0, to record the fact that you no longer have an image.
it can only be freed if all the instances of the class are destroyed
If by "the class" you mean ball, then no. Static members of ball continue to exist regardless of how many instances of ball there are. The only way a static member might be destroyed before program exit is if you do some (implementation-dependent) thing like unloading the dll which contains the class. But in this case the static member is just a pointer, so (1) destroying it will just destroy the pointer, not the pointee, and (2) there is no need to destroy a pointer anyway, it doesn't occupy significant resources.

If you must have the static member pointing to heap-allocated memory, I would make a member a smart pointer.

A static member exists completely independently of all instances of the class it is a member of. You can delete the pointer at any point in the program. Whether this makes sense semantically, is another issue, of course.

I agree with Jonathan M Davis' answer, but another option you could consider is pulling your images and other resources out of your "domain objects" and into a ResourceManager class, or something along those lines.
The ResourceManager could either be static, or instance-based, and would provide the logic to load and delete resources, needed by the rest of our application.
Classes needing resources could just hold a reference or a pointer to the global resource manager, and request resources from the manager, rather than managing them themselves.

Static member variables don't need to be deleted. If you have one within a class, is because you want to use it at any time during the entire life of the programme. Once the programme finishes, the Operating System claims back the total memory assigned to it, including any undeleted memory space.
Of course, if you insist in deleting it, you can create a special static member method for doing it and invoke the method at a desired point in the programme. But I woudn't recommend it to anyone, because it violates the semantic integrity of the static member variables, increasing so the complexity and the likelihood for causing troubles as the programme grows.

Working with a static variable where the memory is dynamically allocated, it is better to go with smart_pointer or a method where memory is cleared manually.
Clearing the memory of static varibles in the destructor will not work for the below case:
As static members exist as members of the class rather than as an instance in each object of the class. So if someone access a static variable using :: and dynamically allocate memory, the destructor will not come in picture and the memory will not get deleted, as there is no object created.

Related

Class destructors and pointer deallocation

I am writing a class (virtual_flight_runtime_environment), and it is mostly non-static, with the exception of one static function for the purposes of a Win32 thread using it as its function. The class declares struct simaircraftdata* aircraftdata (a data struct), and calls 'aircraftdata = new aircraftdata;' in the constuctor (public: virtual_flight_runtime_environment()).
My question is about destructors and memory deallocation. I have written the destructor as such:
~virtual_flight_runtime_environment(void) {
/*..Other code, i.e. closing win32 handles, etc.*/
delete aircraftdata;
}
Now, the class is declared in another function (the DoWork function of a .Net background worker) like so:
virtual_flight_runtime_environment* this_environment = new virtual_flight_runtime_environment;
And just before the end of the function, I call 'delete this_environment;'. Immediately after, 'this_environment' would have gone out of scope, and the desturctor should have been called.
Is this correct? I do notice continued increases in memory usage over time, and I'm wondering if I've done something wrong. Does calling delete on a pointer just make it a null pointer, or does it deallocate the data at the end of it?
Any advice would be appreciated,
Collin Biedenkapp
There is no direct connection between a delete in your program and whether it will directly be visible in say the task manager because the OS tries to optimize memory utilization. When you look in the task manager you will typically see the working set size of your application, this is a measure of how much memory your app has requested but not necessarily how much it is currently using.
And to your question, yes deleting the memory as you did it is the WTG although as others have pointed out using smart pointers is generally much better to handle memory to avoid later headaches.
You're almost correct.
delete this_environment calls the destructor of virtual_flight_runtime_environment. The destructor executes delete aircraftdata.
Right after that, the memory occupied by the instance of virtual_flight_runtime_environment is released.
Please be aware that delete statement doesn't set the pointer to NULL.
So I see no problem in your code given the information in the question.
This looks correct.
Calling delete on your this_environment will cause the destructor of that class to be called before it's memory is deallocated. The destructor deletes the aircraft data. Looks correct.
You might consider instead of having a member variable containing a raw pointer to aircraftdata instead using an auto_ptr or in c++11 unique_ptr which will ensure that it gets deleted automatically when it's containing class is constructed. Look it up, this isn't the place to teach it and it's just a suggestion, not a necessity.
Edit: And I also agree with Pete Becker's comment on the question, which is to question if this needs a pointer at all.
You should indeed explicitely call "delete this_environment". Otherwise, it's only the pointer itself (which exists on the stack) which would be destroyed. The data pointed, on the heap, would still exist.
The other solution is to simply get rid of the pointer and declare your variable as such :
virtual_flight_runtime_environment this_environment;
That way, your object will directly exist on the stack, and its lifetime will depend on the scope in which it is declared - and the destructor will be automatically called at this point, calling in turn the delete for your internal data.

Global Static Dynamically allocated objects C++

I have very specific question about dynamically allocated static global object. In my project i have few object which I need to access from various places across the threads throughout the application lifetime. I want to create the at the application initialization and distroy when application exits. So I tried following,
Header File: MyObjectFactory.h
class MyObjectFactory{
public:
static MyObject* GetMyObject();
};
Source File: MyObjectFactory.cpp
static MyObject* gMyObject = 0;
MyObject* MyObjectFactory::GetMyObject(){
if(gMyObject == 0)
{
gMyObject = new MyObject();
}
return gMyObject;
}
This code seems like working but i want to clear few things.
Object will be created only once and then reference to object will be returned.
( I want this because MyObject encapsulate few system resource like text file)
MyObject gets destroyed when Application exits.
Where would be object created Heap (as I am using new ) or global memory (as I am using static)? Or am I violating any OOP principle?
Is it ok to call MyObjectFactory::GetMyObject() from multiple thread?
Is this a good way to achieve somewhat similar to Singleton?
Please let me know your input.
Thank You so much!
The standard way to achieve both proper destruction and correct initialization with minimal headache uses block-local statics, like this:
foo.hpp:
struct Foo
{
static Foo & get();
// ...
};
foo.cpp:
#include "foo.hpp"
Foo & Foo::get()
{
static Foo impl;
return impl;
}
Now you can say Foo::get() anywhere in your code. No pointers, no dynamic allocations, and nothing gets leaked. A truly static singleton.
Object will be created only once and then reference to object will be returned. ( I want this because MyObject encapsulate few system resource like text file)
MyObject* is a pointer type, not a reference type. gMyObject is a variable of type pointer to MyObject.
MyObject gets destroyed when Application exits.
It does not, noone calls delete on your pointer so you have a leak.
Where would be object created Heap (as I am using new ) or global memory (as I am using static)? Or am I violating any OOP principle?
If you are using new, the object is created at the 'heap'. The static only applies to the pointer to your object, not the object itself.
Is it ok to call MyObjectFactory::GetMyObject() from multiple thread?
It's not, you can cause multiple initializations if you have concurrent threads and the object wasn't constructed yet.
Is this a good way to achieve somewhat similar to Singleton?
It's not. Or maybe it is, but a singleton is usually a bad way to achieve something (and I only said usually).
Object will be created only once and then reference to object will be returned.
If your program is single-threaded, yes (although in your example it returns a pointer not a reference). Otherwise there is a danger of two threads creating separate copies of the object; or in fact of anything else happening, since the behaviour is undefined in that case.
MyObject gets destroyed when Application exits.
No, objects created with new will only be destroyed by delete, never automatically, so this object is leaked. Whether or not that is a problem depends on whether all the resources it uses are automatically reclaimed by the system.
Where would be object created Heap (as I am using new ) or global memory (as I am using static)?
The object is allocated from the free store (aka heap); the pointer to it is static.
Is it ok to call MyObjectFactory::GetMyObject() from multiple thread?
Only if you can ensure that the object has already been created before either of them call it.
Is this a good way to achieve somewhat similar to Singleton?
There's no good way to achieve that in C++. The best approach is to avoid globally accessible objects altogether; create it somewhere, and pass references to whatever needs it.
If you really want a global object, then there are a few options, each with their own deathtraps:
A simple global object. Be careful of the Initialisation Order Fiasco if you have more than one of these, with dependencies between them.
A function containing a static object, returning a reference to this. That is guaranteed to be initialised when you use it, and is thread-safe on a C++11 compliant implementation (and on many earlier implementations too). However, during program shutdown there is a danger that it might be destroyed before other static objects that are still trying to access it - you could perhaps avoid that by dynamically allocating and leaking the object, as in your approach. There may also be some runtime overhead from ensuring thread-safe construction.
A lazily-allocated dynamic object (like you have), as long as you either make sure it's initialised before launching multiple threads, or add thread safety (which isn't entirely straightforward, and will add run-time overhead).

C++ method variable declaration

Currently I'm looking into this C++ source code. I'm not a C++ dev.
void SomeClass::SomeMethod() const
{
vector<Thing> things(count);
...
//Elements are added or replaced in things but no deallocation of things here
}
SomeMethod is called a lot of times. Could anyone confirm that there is no leak and things is allocated only once, reference would be appreciated.
The vector is created everytime you enter the function and destroyed (destroying all objects and freeing all the memory) when it leaves scope (when the function ends). There's no leak, but there's a lot of allocations and deallocations if you call that function frequently.
You have 2 solutions to avoid that:
(preferred) Make this vector a class field (with attribute mutable in order to allow it to be changed by a const method),
Make this vector a static variable.
"things" is a local auto variable.
Another post has a answer for this: Where are the local, global, static, auto, register, extern, const, volatile variables are stored?
Provided Thing is correctly implemented insofar as its destructor and other member functions (especially copy constructor because that's used in vector housekeeping) correctly handle all memory for its data members, what this will do is create a new vector<Thing> on each call to the function.
The resulting local variable things gets correctly freed, including destruction of every Thing member, when the variable goes out of scope (i.e. on function exit).
It's impossible to be more definitive without seeing all the code in the method and in Thing, but this usage is on the face of it correct.
That lays localy in that function. When it goes out of scope, it will delokate the memory by itself; all of the STL containers do.

Dynamic vs non-dynamic class members

In C++, ff I have a class that needs to hold a member which could be dynamically allocated and used as a pointer, or not, like this:
class A {
type a;
};
or
class A {
A();
~A();
type* a;
};
and in the constructor:
A::A {
a = new type();
}
and destructor:
A::~A {
delete a;
}
are there any advantages or disadvantages to either one, aside from the dynamic one requiring more code? Do they behave differently (aside from the pointer having to be dereferenced) or is one slower than the other? Which one should I use?
There are several differences:
The size of every member must be known when you're defining a class. This means you must include your type header, and you can't just use a forward-declaration as you would with a pointer member (since the size of all pointers is known). This has implications for #include clutter and compile times for large projects.
The memory for the data member is part of the enclosing class instance, so it will be allocated at the same time, in the same place, as all the other class members (whether on the stack or the heap). This has implications for data locality - having everything in the same place could potentially lead to better cache utilization, etc. Stack allocation will likely be a tad faster than heap allocation. Declaring too many huge object instances could blow your stack quicker.
The pointer type is trickier to manage - since it doesn't automatically get allocated or destroyed along with the class, you need to make sure to do that yourself. This becomes tricky with multiple pointer members - if you're newing all of them in the constructor, and halfway through the process there's an exception, the destructor doesn't get called and you have a memory leak. It's better to assign pointer variables to a "smart pointer" container (like std::auto_ptr) immediately, this way the cleanup gets handled automatically (and you don't need to worry about deleteing them in the destructor, often saving you from writing one at all). Also, any time you're handling resources manually you need to worry about copy constructors and assignment operators.
With the pointer you have more control, but also more responsibilities. You have more control in the sense that you can decide the lifetime of the object more precisely, while without the pointer the lifetime is essentially equal to the lifetime of the containing object. Also, with the pointer the member could actually be an instance of a subclass of the pointer type.
Performance-wise, using the pointer does mean more memory usage, more memory fragmentation, and dereferencing does take amount of time. For all but the most performance critical code none of this is really worth worrying about, however.
The main difference is that the pointer can potentially point somewhere else.
edit
Laurence's answer isn't wrong, but it's a bit general. In specific, dynamic allocation is going to be slightly slower. Dereferencing through the pointer is likewise going to be very slightly slower. Again, this is not a lot of speed loss, and the flexibility it buys may well be very much worth it.
The main difference is that if you don't use a pointer, the memory for the inner member will be allocated as a part of the memory allocated for the containing object. If you use new, you will get memory in separate chunks (you already seem to have proper creation and destruction of the referenced object down)
You need to understand the implications of default copy constructor and copy assignment operators when using raw pointers. The raw pointer gets copied in both the cases. In other words, you will end up having multiple objects (or raw pointers) pointing to the same memory location. Therefore, your destructor written as is above will attempt to delete the same memory multiple times.
If the member variable should live beyond the lifetime of the object, or if its ownership should be transferred to another object, then the member should be dynamically (heap) allocated using "new". If it is not, then it is often the best choice to make it a direct member of the class in order to simplify code and lessen the burden on the memory-allocator. Memory allocation is expensive.

when to use new in C++?

What's a good policy for when to use "new" to make an instance of a class? I've been hobby programming C++ for a while but I'm still not for sure when is the best time to do this:
MyClass thing(param1, param2);
over this:
MyClass* thing;
thing = new MyClass(param1, param2);
Any advice?
Design-wise, use automatic (stack) allocation as much as possible. Whenever you need to extend the lifetime of an object beyond a certain scope, then dynamically allocate it.
And even so, never dynamically allocate things raw. Always keep them wrapped into some sort of wrapper that implements Scope-Bound Resource Management (SBRM, first known under the dumb/awkward name Resource-Acquisition Is Initialization or RAII.) That is, dynamic allocations should be kept in automatic objects that will clean up automatically!
A good example of this is std::vector: you cannot leak the memory internal to a vector, because it's destructor is run in every scenario when memory should be free'd, and it will free it for you. auto_ptr is the first and only smart pointer available in the standard library, but it's pretty bad. Better is to use shared_ptr, or many of the other popular smart pointers available in Boost and/or TR1 and/or C++0x.
Performance-wise, objects allocated on the stack can be done so very quickly (the stack size is increased per-function-call, so all the required memory has been allocated up-front by a simple move of a pointer.) Contrarily, dynamic allocation generally requires much more time. It's quite possible to get speedy dynamic allocations with custom allocation schemes, but even the best will still be slower than stack allocation.
Occasionally, you might find you spend too much time copying objects around. In this case, it may be worth it to dynamically allocate it and merely move pointers around. However, please note I said "find". This kind of change is something you find by profiling and measuring, never guessing.
So: Automatic allocation when possible, dynamic allocation when needed.
The first approach creates a local instance on the stack that goes away when the calling function exits. The second creates an instance that stays on the heap until (and if) you explicitly release it again. The choice depends on what kind of control and lifetime you want for your object.
The rule of thumb is: if it works without new, don't use new.
In general: you don't need to use new if you plan to delete the object in the same scope. If the object is quite large, you may want to use new.
You may want to look into the difference between heap and stack memory if you want to know the details.
First, ask yourself the question, does it make sense for the object to be copied when another function wants it?
If it makes sense to copy the object, your best bet is to create everything on the stack or as member variables and then just pass copies around when needed.
If it does not make sense to copy the object, you'll need to use new form so that you can safely pass the pointer to the object. You have to use a pointer (or reference) because as noted it does not make sense to copy the object.
There are two exceptions I'm aware of:
If you know the object isn't going to be used after the current function is finished, you can create the object on the stack so that it is deleted. Just make very sure nobody holds on to a pointer to it afterwards! (I rarely find this is the case, but it happens)
If the object is used internally by another class which itself shouldn't be copied around, you can just put it in as a member variable. Since the object it is in won't be copied, and its only for internal use that will be safe.
MyClass thing(param1, param2); //memory for thing is allocated on the process stack(static allocation)
MyClass* thing;
thing = new MyClass(param1, param2); //memory is allocated dynamically on the heap(free store) for thing
The difference lies here:
int main()
{
{
MyClass thing(param1, param2); //thing is local to the scope
} //destructor called for thing
//cannot access thing (thing doesn't exist)
}
int main()
{
{
MyClass* thing;
thing = new MyClass(param1, param2);
}
//the object pointed to by thing still exists
//Memory leak
}
For large objects you must allocate memory dynamically(use new) because the process stack has a limited size.