Object Lifetime

How would I create an object that has the lifetime of a global variable? I need this object to retains its spot in memory, but it must not be declared global.

Thanks. :)
Last edited on
Use the "new" operator. It creates memory on the free store. If you do this, you would also need to use the delete operator to remove the memory you created.

When you do this, it creates a memory location that you would access via a pointer and pointer notation.
A local variable within main will exist for the duration of main which is the lifetime of the program.
1
2
3
4
5
int main ()
{ int somevar;
   // do something using somevar
   return 0;
}

Thansk pogrady, I'll try that out.

AbstractionAnon, I am aware of that, but the object is deleted at the end of scope. I am doing this within a function that is called by main. I should have done this a different way, but that is how it has to be done.
Last edited on
Then declare it in main and pass it to your function as an argument.

If you call new within your function, the pointer you set will go out of scope when your function exits. If you call new from main, then you're going to have to pass it to your function also. Anytime you call new, you introduce the possibility of introducing a memory leak by not calling delete.
closed account (zb0S216C)
I would suggest creating the object inside a name-space. For instance:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
namespace Global 
{
    int Some_Data(10);
}

int main( )
{
    int Some_Function(int Data);
    Global::Some_Data = Some_Function(Global::Some_Data);
}

int Some_Function(int Data)
{
    return(Data + Data);
}

Note that "Some_Function( )" was implemented so that it does not depend on "Global::Some_Data".

Wazzak
This container, the vector, will be holding a large amount of pointers to Member objects. Wouldn't I have to declare a new object for every object I want to push into the vector from the file?

Anyway, I've found my solution.
closed account (zb0S216C)
Pushing multiple pointers to class data members has little sense since 1 pointer to a data member can reference all instances of a class:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
struct Some_Class
{
    int A_;
};

int main( )
{
    int(Some_Class:: *Pointer)(&Some_Class::A);
    
    Some_Class A;
    Some_Class B;

    A.*Pointer = 10;
    B.*Pointer = 20;
}

Wazzak
Last edited on
Topic archived. No new replies allowed.