2

Please explain memory allocation with instance creation

class simpleTestFactory
{
    public: 
    static simpleTest* Create()
    {
        return new simpleTest();
    }
}

class simpleTest
{
    private:
    int x,y,z;
    public:
    int printTest()
    {
        cout<<"\n This test program";
    }
}

int main()
{

    simpleTest* s1=simpleTestFactory::Create();
    .
    .   
    s1=simpleTestFactory::Create();
}   

In the main function we are creating instance for the simpleTest with create static function. Again we are creating another instance for the same object.

In this case the first created instance memory would be deleted??

otherwise how to avoid memory issues??

thar45
  • 3,518
  • 4
  • 31
  • 48
  • Use a smart pointer such as `shared_ptr` or `unique_ptr` – Nick May 02 '12 at 10:54
  • i need to create single instance for the entire project, How can i use created instance reference for multiple objects. – thar45 May 03 '12 at 04:54

4 Answers4

2

In this case the first created instance memory would be deleted?

No, it won't. You have to deallocate it yourself by calling delete, or by using a smart pointer in the first place.

(I assume that s1 is of type simpleTest*, i.e. a pointer to simpleTest, as otherwise your code is not valid C++.)

NPE
  • 486,780
  • 108
  • 951
  • 1,012
2

First of all your program won't compile as you are passing pointer to an object. It should be:

simpleTest *s1 = simpleTestFactory::Create();
           ^^^

The memory management has to be done manually in C++.

delete s1;  // do it before new allocation to s1.

Also remember that, in C++ creating an object with new is not mandatory. It can be as simple as:

simpleTest obj;  // automatic object, no explicit deallocation

[For automatic garbage collection you can also use smart pointers].

Community
  • 1
  • 1
iammilind
  • 68,093
  • 33
  • 169
  • 336
2

Try singleton type pattern. You can create instance only if it is not already created. Not sure about your use case.

Mayank
  • 399
  • 1
  • 3
  • 6
0

Singleton pattern also assumes that object instance will be deleted. Therefore you need to implement special method.

Considering Thangaraj question, don't forget ';' after class definitions. Yes, you must explicitly delete objects through the delete call. To avoid this, you can use smart pointers.

besworland
  • 747
  • 2
  • 7
  • 17