Link to home
Create AccountLog in
Avatar of sukhoi35
sukhoi35

asked on

How to assign memory to static members of a class? - C++

I have a class with few static char* variables. How do I assign and free their memory? Please explain with sample code.
Avatar of jkr
jkr
Flag of Germany image

Declare them with the class and provide an instatiation in your immplementation, e.g.
class foo {

public:

  foo () { text = "test"; }

  // ...

protected:
  static char* text;
};

// ...

// this is where the static member is placed
char* foo::text;

Open in new window

You can do it exactly as you normally would with regular char* variables. Static variables operate identically to regular variables except you that you can only reference static variables from within static functions/methods.
SOLUTION
Avatar of jkr
jkr
Flag of Germany image

Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
See answer
Avatar of phoffric
phoffric

Here are links with examples showing how to use new, new[], delete, and delete[].

Just replace the example type with char.

// http://www.cplusplus.com/reference/std/new/operator%20new/

// operator new example
#include <iostream>
#include <new>
using namespace std;

struct myclass {myclass() {cout <<"myclass constructed\n";}};

int main () {

   int * p1 = new int;
// same as:
// int * p1 = (int*) operator new (sizeof(int));

   int * p2 = new (nothrow) int;
// same as:
// int * p2 = (int*) operator new (sizeof(int),nothrow);

   myclass * p3 = (myclass*) operator new (sizeof(myclass));
// (!) not the same as:
// myclass * p3 = new myclass;
// (constructor not called by function call, even for non-POD types)

   new (p3) myclass;   // calls constructor
// same as:
// operator new (sizeof(myclass),p3)

   return 0;
}

// ==========================
// http://www.cplusplus.com/reference/std/new/operator%20new[]/
// operator new[] example
#include <iostream>
#include <memory>
#include <new>
using namespace std;

struct myclass {myclass() {cout <<"myclass constructed\n";}};

int main () {
  // uses first version:
  int * p1 = new int[5];

  // uses second version:
  int * p2 = new (nothrow) int[4];

  // uses third version:
  pair <myclass*,ptrdiff_t> p3 = get_temporary_buffer<myclass>(3);
  new (p3.first) myclass[3];   // calls constructors
  return_temporary_buffer(p3.first);

  return 0;
}

// ==========================
// http://www.cplusplus.com/reference/std/new/operator%20delete/

// operator delete example
#include <iostream>
#include <new>
using namespace std;

struct myclass {
  myclass() {cout <<"myclass constructed\n";}
  ~myclass() {cout <<"myclass destroyed\n";}
};

int main () {
  myclass * pt;

  pt = new myclass;
  delete pt;

  return 0;
}


// ==========================
// http://www.cplusplus.com/reference/std/new/operator%20delete[]/

// operator delete[] example
#include <iostream>
#include <new>
using namespace std;

struct myclass {
  myclass() {cout <<"myclass constructed\n";}
  ~myclass() {cout <<"myclass destroyed\n";}
};

int main () {
  myclass * pt;

  pt = new myclass[3];
  delete[] pt;

  return 0;
}

Open in new window

If you are referring to the syntax required to initialise a static it's like this.
class my_static
{
   static char * str;
};

char * my_static::str = "hello world"; // doesn't need to be free'd

Open in new window

Avatar of sukhoi35

ASKER

Hi Experts,
Thanks for your responses. I actually need to dynamically allocate memory to a static char* in one of my methods. I would like to know how to release the memory at the end of the program i.e. before the application exits? I mean, where do I include the delete?
Inside  the destructor,

if (p!=NULL)
 delete[ ] p;           // if Allocating array of chars
ASKER CERTIFIED SOLUTION
Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
SOLUTION
Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
atexit is not a good advice regarding OOP rules.
A class have to manage its own allocations, it must not depend on external actions. Otherwise it is not ready to be reused in another context.
In case I am using the 'static char* charBuffer' in a fread operation, something like:

FILE *fpointer = fopen(filePath, "rb");
fread (charBuffer,1,fileLen,fpointer);

Do I need to worry about releasing the charBuffer memory here also?

Please clarify.
If you have, for example:
    charBuffer = new char [fileLen+1];
Then when you are done processing charBuffer, you should release it.
SOLUTION
Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
If you use my solution, you wouldn't have to free allocated buffer after fread, as it will be done when last object of its class will be destroyed. Then you could use the same buffer for further read operations.
@phoffric : your comment is right, but not Object Oriented.
Thanks
>> atexit is not a good advice regarding OOP rules.

The question is about releasing memory allocated to a static... at this point we are not even discussing OOP since statics are NOT instance objects and to presume they are and then allocate de-allocate in an instance constructor is a thread race condition waiting to happen. In other words, the very essence of what the asker is trying to do is probably flawed but using atexit to perform final clean-up is not itself an intrinsically bad idea -- although, as I pointed out, also not absolutely necessary since the OS will perform this anyway.

>> @phoffric : your comment is right, but not Object Oriented.

In all fairness a separate object is also not required either... one could just use a vector.
@evilrix : author start with "I have a class with few static char* variables".

So, it seems that we were talking about OOP. In OOP static members must be considered as class part and managed exclusively by the class. Otherwise, they've nothing to do inside it, and it's rather a design issue.

It's more than a reusability condition, it's a reliability question. Of course, developpers who manage software with several thousand lines of code can forget that without great pain. But when you deal with millions line of code, everything must be cleanly done, otherwise it never works fine. As well starting with the good rules.
>> So, it seems that we were talking about OOP.

static variables are not class instance variables... they belong to the class and not any specific instance. They are just variables with class scope. By their nature, static class members do not belong to any instance therefore they are not bound to the same OOP rules as instance variables. To imply otherwise is very misleading. Why do you think the syntax for initialising a static class member does not use any constructor? There is very little difference between a class static and a namespace level variable in terms of semantics and, to a large extent, syntax.

If you wish to debate this further we can, but not here... post in our expert thread and we (including the other experts) can discuss it further as you wish.

Thanks.
I absolutely not agree with your static member considerations...but I've lost exert thread link (and I couldn't retrieve it in my comment history ?). Can you share it again please?
Trying to post in this thread, I had the following message:
"You do not have the proper permissions to post a Comment in this Topic Area"
??
There has been an issue with this weeks release that has caused a number of permissions problems - including breaking some users access to PDs. It will; hopefully, be resolved with this weeks release... normally pushed around Thursday.