Question about delete() a class instance and its static methods/variables - c++

Consider this class for demonstration purposes:
class test{
private:
int y;
HANDLE handle;
static int x;
public:
test()
int add();
static int sub();
}
test::test() {
[....]
sub = 1;
handle = (HANDLE)_beginthreadex(NULL,0,&test::sub,NULL,0,0);
}
test::sub() {
[....]
_endthreadex(0)
}
I am a little unsure about static methods/variables and I now have a few questions;
1) If I create a class instance of test, and then call delete test, does the static variable get cleaned up too? If not, do I need to cleanup all static variables manually in the destructor using delete() (or is it free())?
2) when the thread running sub() terminates with _endthreadex, is there any manual cleanup to be done on the static method? As you can see, the handle variable is refering to the thread.
Thanks in advance

Static variables have program lifetime. They are created when the program starts, and destroyed when the program ends. Only one exists, and it's not in the individual objects.

The keyword 'static', in this instance, implies that there is only a single instance of the variable in memory and it 'belongs' to class test. Long after the instance of 'test' is gone, the variable test::x will remain around and is accessible by any other instances of 'test' and the static 'sub' function (as it is a private variable). No cleanup is necessary, as there is only this single instance in memory.
If the reason for making it static is so it is accessible in 'sub', you could instead pass it in as a parameter. Alternatively, you could pass in the 'test' instance to the thread method and then it would no longer need to be static as you would be able to call non-static functions on the object.

the static variable persist from one instance of the class to another that's why they are static. If you want them to be instance specific then remove the static keyword.

You should never attempt to deallocate a static variable. If you find yourself wanting/needing to do this, then you probably don't really want to use static at all.

The static int would reside in the BSS or Uninitialised Data Section and so, as others have suggested, it will be available fot the lifetime of the program.

Related

Static variable and memory allocation in class and its use

I am new with c++ and I don't completely understand the concept of static variables.
I have a static variable in a class.
class FCCommunication : public OEMThread
{
public:
FCCommunication();
static bool MASTER;
}
I am initializing my code and allocation memory to the FCCommunication in the source file using following two statements
FCCommunication * FCObject = 0;
FCObject = new FCCommunication();
now the question for me is that what will happen if I try to access MASTER variable before the object and memory allocation will be done like this
if(FCCommunication::MASTER)// this gets called before dynamic memory allocation.
{
//do something here.
}
Static member variables are allocated as any other non-member variable with static storage duration. Meaning that they end up in a chunk of data initialized before the program is started, most often called either .bss or .data, depending on if the initalizer is a zero value or not.
So the static member variable is not actually allocated together with the class and the value you initialize it to is set by code executing before the rest of the class is even allocated.
This means that you can actually access static members no matter if any instance of the class exists or not. You can think of them as "global variables with restricted access and scope", because that is exactly what they are.
Meaning that your code is fine.
C++ member static variables (of a class) belong to all instance of that class, and they are initialized before any instances of that class are initialized. So, you can use both FCCommunications::MASTER and FCObject->MASTER to access those static variables with no differences.
One thing you should be careful about is that you have to define those static variable separately. That say, you have to do something like this, outsides the class definition:
bool FCCommunications::MASTER = false;
static members are members initialied to zero for first time it is initialized...
IN otherr words , they belongs to a common pool.
any other object can access it.
scope is within the class
the lifetime is the lifetime of the program.

How to access the variable from another function in a class

So I have experience using programming languages and just switched over to C++. Now I have created a few working applications but I always stumble upon the same problem. I don't exactly know what everything is called in the code. You have a class which obvious to see since the has written class before it. And you also have some sort of functions attached to the class are these called instances? And is the class the object it referring to by for example class::function.
But my main question was how can I access the variables from another function within the same class file. I have included an example below explaining what I want to achieve. I already tried a lot of things and googled a lot. I tried code pasting code creating setting and getting functions, calling the class to get and set the variable but I can't get it to work. I've spend a lot of time fixing this very basic problem. Could someone explain me what is called what in this code (Class,Object,Instance). And explain me the most efficient way to receive data from another function in the same .cpp file.
Thanks
load_data.h
#pragma once
class load_data
{
public:
static int data[13];
load_data();
static void test2();
};
load_data.cpp
#include "load_data.h"
#include "abc.h"
load_data::load_data()
{
int data[3]; // Initializing the array
data[0] = abc::LoadImage("textures/1.png");
data[1] = abc::LoadImage("textures/2.png");
data[2] = abc::LoadImage("textures/3.png");
}
void load_data::test2()
{
abc::CreateSprite(1, data[0]);
abc::SetSpritePosition(1, 0, 0);
abc::SetSpriteScale(1, 3, 3);
// Now I get an error saying it has no data. Which however is set in
// load_data(). But since each function gets its own variables this one will be empty.
abc::CreateSprite(2, data[1]);
abc::SetSpritePosition(2, 64, 64);
abc::SetSpriteScale(2, 3, 3);
abc::CreateSprite(3, data[2]);
abc::SetSpritePosition(3, 128, 128);
abc::SetSpriteScale(3, 3, 3);
}
Change your load_data() constructor to the following (currently, your creating a new data[] variable that is locally scoped to your load_data() constructor, which gets initialized instead of your object's data[] (gets "eclipsed"). Your subsequent call to test2() fails when it accesses data[] because the other, local data[] was initialized instead. Also, fyi, the local data[] is destroyed when load_data() returns (because it is an auto/stack variable that falls out of scope).
load_data::load_data()
{
//int data[3]; // Initializing the array
data[0] = abc::LoadImage("textures/1.png");
data[1] = abc::LoadImage("textures/2.png");
data[2] = abc::LoadImage("textures/3.png");
}
you also have some sort of functions attached to the class are these
called instances?
An object is an instance of a class. A class defines the object type, which consists of state variables, and operations for them (known as "member functions" or "methods").
An object's methods are called through a handle to the instance. IE, an instantiated variable:
load_data ld = new load_data();
ld.test2();
And is the class the object it referring to by for example
class::function.
This notation is for explicitly qualifying a method name. It helps resolve naming conflicts and should only be used when needed (otherwise it is implicit).
But my main question was how can I access the variables from another
function within the same class file.
...
But since each function gets its own variables this one will be empty
All functions of a class share the class'es (member) variables. An given instance of the class has the only copy of those member variables (ie, their specific values/memory to that instance), so all method calls through a specific instance variable (say ld) of load_data will refer to the same data[] array (so load_data ld1, ld2 would each have their own copies). Functions can, and usually do, declare their own variables to help assist in computing the task they perform (bools, counters, etc...). These such variables, as mentioned before, are scoped to that function, meaning they're no longer allocated and get destroyed when the function returns (they are auto-variables).
And you also have some sort of functions attached to the class are
these called instances?
No. the functions inside of the class are called "class member function" or just "member functions". An instance is a copy of that object (read class) in memory. So in short:
class A {
public:
void fun (void); ///< This is a class member function
};
void main (int argc, char *argv[]) {
A a; ///< a is an instance of object A
}
And is the class the object it referring to by for example
class::function.
The class defines the object. In the above snipped, A is an object.
But my main question was how can I access the variables from another
function within the same class file.
You need to do some reading on variable scope. In your above example the data array is local to the constructor. It doesn't exist within the object, only within that function. So as soon as the constructor finishes, the variable goes out of scope and is lost. In order to keep it in the object's scope you would need to declare it within the object.
class load_object {
public:
// The same
private:
int load[3];
};
Cheers

Setting private member pointer to the same class as NULL?

I came across the following structure in a C++ library:
In myClass.h
class myClass {
public:
static myClass* Instance();
.
.
private:
static myClass* _instance;
.
.
};
and in myClass.cpp
myClass* myClass::_instance = NULL;
// followed by the all other functions..
myClass::myClass() {
.
.
}
myClass* myClass::Instance() {
if (_instance == NULL) {
.
.
}
.
.
}
So what is the use of making the _instance to be NULL pointer outside any function? And when is this line of code executed?
Thank you.
Edit:
Adding the main function. And the instance function in myClass.cpp that checks for the value of the pointer. Still don't understand when the pointer get set to NULL though.
int _tmain(int argc, T_CHAR* argv[]) {
myClass* instance = myClass::Instance();
.
.
.
return 0;
}
So what is the use of making the _instance to be NULL pointer outside any function?
Static data members usually have to be defined, in the namespace containing their class, in one source file; they are subject to the One Definition Rule, and so must have exactly one definition in any program that uses them. This is that definition.
Initialising it with NULL makes sure it's initially null, so that the Instance() function can determine whether the instance has been created yet. This isn't strictly necesssary since, like all static variables, it will be zero-initialised whether or not you explicitly provide an initialiser.
And when is this line of code executed?
During static initialisation, before any other code in the program; since it's a trivial type with a constant initialiser.
I have stumbled upon something like this once. It was something similar to singleton. The reason (as explained by the person doing it) was that he specifically wanted to initialize instance at the first getInstance() function call and he wanted to make sure that the _instance pointer will be at first initialized to NULL (and not some garbage from memory) so that the check
if (_instance == NULL)
in the function works properly.
I am not sure this is the case here, but it's possible.
myClass* myClass::_instance = NULL;
the code attempts to initialize the static member variable.
It's an initialisation, ensuring that the pointer starts life with the value NULL from the very beginning of the program.1
It gives the pointer an invalid, but recognisable and testable value before some useful pointer value is assigned to it later on during the program. This way, you can safely test the pointer to see whether it was yet given said useful value.
In this case, since you are showing a singleton, "later" means "when an instance of myClass is first requested" using some myClass::getInstancePlease() function that you have not shown.
It is more common to implement a singleton with a function-static instance, rather than a class-static pointer to some [probably dynamically-allocated] instance.
1 As an object with static storage duration, it would do so anyway; therefore, this initialisation is actually completely pointless beyond documenting programmers' intent.
Static keyword means it is being shared by all the objects that will be instantiated by the class. Hence you need to initialize it outside any function.Static states that it is a class variable shared between all the instance of the class. It is opposite to instance variables, which each instance has its own copy. To access a class variable, there are two ways. 1) a_class::static_variable 2) a_class a; a.static_variable. The initialization must go in the source file (.cpp) rather than in the header.
Because it is a static variable the compiler needs to create only one copy of it. If you don't, you get a link error. If that is in a header you will get a copy in every file that includes the header, so get multiply defined symbol errors from the linker.
Static data members are not part of objects of a given class type; they are separate objects. As a result, the declaration of a static data member is not considered a definition. The data member is declared in class scope, but definition is performed at file scope.

Should I prefer to use a static class variable or a static variable inside a class method?

The question is, what would be the best or maybe a better practice to use. Suppose I have a function, which belongs to some class and this function needs to use some static variable. There are two possible approaches - to declare this variable as class's member:
class SomeClass
{
public:
....
void someMethod();
private:
static int m_someVar;
};
SomeClass::someMethod()
{
// Do some things here
....
++m_someVar;
}
Or to declare it inside the function.
class SomeClass
{
public:
....
void someMethod();
};
SomeClass::someMethod()
{
static int var = 0;
++m_someVar;
// Do some things here
....
}
I can see some advantages for the second variant. It provides a better encapsulation and better isolates details of an implementation. So it would be easier to use this function in some other class probably. And if this variable should be modified only by a single function, then it can prevent some erroneous data corruption from other methods.
While it's quite obvious, that the first variant is the only one to use when you need to share a static variable among several methods (class functions), the question pertains the case when a static variable should be used only for a single function. Are there any advantages for the first variant in that case? I can think only about some multi threading related stuff...
It's simple - use a static member if, logically, it belongs to the class (sort of like instanceCounter) and use a static local if it logically belongs to a function (numberOfTimesThisMethodWasCalled).
The choice of static or not depends completely on the context. If a particular variable needs to be common among all the instances of a class, you make it static.
However, if a variable needs to be visible only in a function and needs to be common across every call of the function, just make it a local static variable.
The difference between static data members and static variable in a function is that first are initialized at start-up and the second first time the function is called (lazy initialization).
Lazy initialization can create problem when a function is used in a muti-threaded application, if it is not required by the design I prefer to use static members.

Global instance of a class in C++

As the title says. How would I create an instance of a class that is globally available(for example I have a functor for printing and i want to have a single global instance of this(though the possibility of creating more)).
Going to all the effort of making a singleton object using the usual pattern isn't addressing the second part of your question - the ability to make more if needed. The singleton "pattern" is very restrictive and isn't anything more than a global variable by another name.
// myclass.h
class MyClass {
public:
MyClass();
void foo();
// ...
};
extern MyClass g_MyClassInstance;
// myclass.cpp
MyClass g_MyClassInstance;
MyClass::MyClass()
{
// ...
}
Now, in any other module just include myclass.h and use g_MyClassInstance as usual. If you need to make more, there is a constructor ready for you to call.
First off the fact that you want global variables is a 'code smell' (as Per Martin Fowler).
But to achieve the affect you want you can use a variation of the Singleton.
Use static function variables. This means that variable is not created until used (this gives you lazy evaluation) and all the variables will be destroyed in the reverse order of creation (so this guarantees the destructor will be used).
class MyVar
{
public:
static MyVar& getGlobal1()
{
static MyVar global1;
return global1;
}
static MyVar& getGlobal2()
{
static MyVar global2;
return global2;
}
// .. etc
}
As a slight modification to the singleton pattern, if you do want to also allow for the possibility of creating more instances with different lifetimes, just make the ctors, dtor, and operator= public. That way you get the single global instance via GetInstance, but you can also declare other variables on the heap or the stack of the same type.
The basic idea is the singleton pattern, however.
Singleton is nice pattern to use but it has its own disadvantages. Do read following blogs by Miško Hevery before using singletons.
Singletons are Pathological Liars
Root Cause of Singletons
Where Have All the Singletons Gone?
the Singleton pattern is what you're looking for.
I prefer to allow a singleton but not enforce it so in never hide the constructors and destructors. That had already been said just giving my support.
My twist is that I don't use often use a static member function unless I want to create a true singleton and hide the constr. My usual approach is this:
template< typename T >
T& singleton( void )
{
static char buffer[sizeof(T)];
static T* single = new(buffer)T;
return *single;
}
Foo& instance = singleton<Foo>();
Why not use a static instance of T instead of a placement new? The static instance gives the construction order guarantees, but not destruction order. Most objects are destroyed in reverse order of construction, but static and global variables. If you use the static instance version you'll eventually get mysterious/intermittent segfaults etc after the end of main.
This means the the singletons destructor will never be called. However, the process in coming down anyway and the resources will be reclaimed. That's kinda tough one to get used to but trust me there is not a better cross platform solution at the moment. Luckily, C++0x has a made changes to guarantee destruction order that will fix this problem. Once your compiler supports the new standard just upgrade the singleton function to use a static instance.
Also, I in the actual implemenation I use boost to get aligned memory instead of a plain character array, but didn't want complicate the example
The simplest and concurrency safe implementation is Scott Meyer's singleton:
#include <iostream>
class MySingleton {
public:
static MySingleton& Instance() {
static MySingleton singleton;
return singleton;
}
void HelloWorld() { std::cout << "Hello World!\n"; }
};
int main() {
MySingleton::Instance().HelloWorld();
}
See topic IV here for an analysis from John Vlissides (from GoF fame).