Home >Backend Development >C++ >When Should I Use the `new` Keyword in C ?
Understanding the Need for the 'new' Keyword in C
C introduces the 'new' keyword for memory management, offering control over object creation and allocation. To understand its usage, let's explore two methods:
Method 1: Using 'new'
Using 'new' allocates memory for an object on the free store (heap), which provides the following:
MyClass* myClass = new MyClass(); myClass->MyField = "Hello world!";
Method 2: Without 'new'
Declaring an object without 'new' allocates it on the stack, which is temporary storage for local variables. This approach has the following characteristics:
MyClass myClass; myClass.MyField = "Hello world!";
Choosing the Right Method
The choice depends on the desired memory management and object durability requirements.
Use 'new' if:
Avoid 'new' if:
Rule of Thumb for Memory Management:
To prevent memory leaks, adopt the practice of pairing every 'new' with a 'delete' statement. This ensures proper memory cleanup and avoids potential issues.
Foobar *foobar = new Foobar(); // ... delete foobar; // Cleanup the allocated memory
The above is the detailed content of When Should I Use the `new` Keyword in C ?. For more information, please follow other related articles on the PHP Chinese website!