When to Utilize "new" in C ?
As a developer transitioning from C#/Java, understanding object instantiation in C can be perplexing. This article clarifies when to employ the "new" operator and when to refrain from it.
Using "new": Ensuing Object Longevity
Use "new" when you want an object to persist until it's explicitly deleted. Without "new," the object will be destroyed once it falls out of scope. Consider the following examples:
void foo() { Point p = Point(0,0); // p is destroyed here } for (...) { Point p = Point(0,0); // p is destroyed after each iteration }
Using "new" for Arrays
Arrays in C are allocated in-place (i.e., on the stack). However, if you need to create an array with a size determined at runtime, you must allocate it using "new."
void foo(int size) { Point* pointArray = new Point[size]; ... delete [] pointArray; }
In-Place Allocation (Without "new")
In-place allocation is preferable for performance reasons. It occurs automatically for objects declared within classes.
class Foo { Point p; // p will be destroyed when Foo is };
Remember that allocating and freeing objects using "new" is more computationally intensive than in-place allocation. Use it only when necessary to avoid unnecessary overhead.
The above is the detailed content of When Should I Use the 'new' Operator in C ?. For more information, please follow other related articles on the PHP Chinese website!