Home > Backend Development > C++ > When Should I Use the 'new' Operator in C ?

When Should I Use the 'new' Operator in C ?

DDD
Release: 2024-11-30 10:51:11
Original
811 people have browsed it

When Should I Use the

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
}
Copy after login

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;
}
Copy after login

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
};
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template