When Do You Need the new Keyword in C ?
In C , you have two options for creating objects: using the new keyword or not.
Using new
MyClass* myClass = new MyClass();
myClass->MyField = "Hello world!";
Copy after login
- Allocates memory for the object on the heap (free store).
- Requires explicit deletion to free the allocated memory.
- Memory remains allocated until deleted, even if the object goes out of scope.
Not Using new
MyClass myClass;
myClass.MyField = "Hello world!";
Copy after login
- Allocates memory for the object on the stack.
- No explicit deletion required.
- Memory is freed automatically when the object goes out of scope.
Choice Considerations
Which method to use depends on your specific needs:
-
Use new:
- To create objects on the heap.
- To return pointers to objects from functions.
-
Don't use new:
- To avoid managing memory manually and potential memory leaks.
- To create objects that will not leave the current scope.
Additional Notes
- Using new requires using delete to free the allocated memory. This is to prevent memory leaks.
- new is commonly used to create objects on the heap, while not using new is typically used for stack-allocated objects.
- The stack has less memory capacity than the heap, so allocating too many objects on the stack can lead to a stack overflow.
The above is the detailed content of When Should You Use the `new` Keyword in C ?. For more information, please follow other related articles on the PHP Chinese website!