Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why should/shouldn't I use the "new" operator to instantiate a class, and why?

I understand that this may be construed as one of those "what's your preference" questions, but I really want to know why you would choose one of the following methods over the other.

Suppose you had a super complex class, such as:


class CDoSomthing {

    public:
        CDoSomthing::CDoSomthing(char *sUserName, char *sPassword)
        {
            //Do somthing...
        }

        CDoSomthing::~CDoSomthing()
        {
            //Do somthing...
        }
};

How should I declare a local instance within a global function?


int main(void)
{
    CDoSomthing *pDoSomthing = new CDoSomthing("UserName", "Password");

    //Do somthing...

    delete pDoSomthing;
}

-- or --


int main(void)
{
    CDoSomthing DoSomthing("UserName", "Password");

    //Do somthing...

    return 0;
}
like image 809
NTDLS Avatar asked Feb 21 '09 04:02

NTDLS


People also ask

Why do we use the new operator when instantiating an object?

The new operator instantiates a class by allocating memory for a new object and returning a reference to that memory. The new operator also invokes the object constructor.

Why do we need to instantiate a class?

Instantiate in Java means to call a constructor of a Class which creates an an instance or object, of the type of that Class. Instantiation allocates the initial memory for the object and returns a reference.

What does it mean to instantiate a class?

Instantiation is the creation of a new instance of a class and is part of object-oriented programming, which is when an object is an instance of a class. Think of the generic employee. When a true employee is hired, they inherit the properties of the generic Employee class.

What is the purpose of the new operator in C ++?

new operator. The new operator denotes a request for memory allocation on the Free Store. If sufficient memory is available, a new operator initializes the memory and returns the address of the newly allocated and initialized memory to the pointer variable.


2 Answers

Prefer local variables, unless you need the object's lifetime to extend beyond the current block. (Local variables are the second option). It's just easier than worrying about memory management.

P.S. If you need a pointer, because you need it to pass to another function, just use the address-of operator:

SomeFunction(&DoSomthing);
like image 50
Mark Ransom Avatar answered Oct 21 '22 01:10

Mark Ransom


There are two main considerations when you declare a variable on the stack vs. in the heap - lifetime control and resource management.

Allocating on the stack works really well when you have tight control over the lifetime of the object. That means you are not going to pass a pointer or a reference of that object to code outside of the scope of the local function. This means, no out parameters, no COM calls, no new threads. Quite a lot of limitations, but you get the object cleaned up properly for you on normal or exceptional exit from the current scope (Though, you might want to read up on stack unwinding rules with virtual destructors). The biggest drawback of the stack allocation - the stack is usually limited to 4K or 8K, so you might want to be careful what you put on it.

Allocating on the heap on the other hand would require you to cleanup the instance manually. That also means that you have a lot of freedom how to control the lifetime of the instance. You need to do this in two scenarios: a) you are going to pass that object out of scope; or b) the object is too big and allocating it on the stack could cause stack overflow.

BTW, a nice compromise between these two is allocating the object on the heap and allocating a smart pointer to it on the stack. This ensures that you are not wasting precious stack memory, while still getting the automatic cleanup on scope exit.

like image 44
Franci Penov Avatar answered Oct 20 '22 23:10

Franci Penov