0

When should I use the new-operator?
In my example I get the same result using two different methods:

#include <iostream>
int main() {
    int *p1;
    int n1 = 5;
    p1 = &n1;

    int *p2;
    p2 = new int;
    *p2 = 5;

    std::cout << *p1 << std::endl;
    std::cout << *p2 << std::endl;
    return 0;
}
Evgenij Reznik
  • 17,916
  • 39
  • 104
  • 181
  • 6
    Don't, unless you run into a situation when you absolutely must (you'll know). In modern C++, this is rarely needed. – Luchian Grigore May 29 '13 at 22:55
  • 9
    If you have to ask, you probably don't need it yet. – milleniumbug May 29 '13 at 22:56
  • 1
    Some people use it to extend the life duration of objects. However, they run into danger of giving those objects immortality and finally turning them into zombies which take your "memoryyyy..." – Sceptical Jule May 29 '13 at 23:04
  • As of C++14, under normal circumstances, absolutely never. In C++11, you can get away with it when initializing a `std::unique_ptr`. In C++03, there's still a lot to choose from to avoid using it. – chris May 29 '13 at 23:13
  • @chris that's interesting, do you mind giving some context? – Adrian Panasiuk May 29 '13 at 23:16
  • @AdrianPanasiuk, Because RAII is more exception safe, typically extremely low overhead, and often clearer. What kind of context are you looking for? There are very few situations in which RAII is not desirable. – chris May 29 '13 at 23:19
  • @AdrianPanasiuk: I presume he's referring to the new `make_unique` helper function. – Ben Voigt May 29 '13 at 23:37
  • possible duplicate of [C++ dynamically allocated memory](http://stackoverflow.com/questions/8504070/c-dynamically-allocated-memory) – AnT stands with Russia May 30 '13 at 00:07

6 Answers6

1

The purpose of using dynamically allocated memory is one (or many) of the following

  • Run-time control over object's lifetime. E.g. the object is created manually by new and destroyed manually by delete at user's desire.
  • Run-time control over object's type. E.g. you can deside the actual type of polymorphic object at run-time.
  • Run-time control over objects' quantity. E.g. you can decide the array size or the number of elements in the list at run-time.
  • When the object is simply too big to be reasonably placed into any other kind of memory. E.g. a large input-output buffer that is too big to be allocated on stack

In your specific example none of these reasons apply, which means that there's simply no point in using dynamic memory there.

AnT stands with Russia
  • 312,472
  • 42
  • 525
  • 765
  • I only disagree with your third bullet. STL containers allow for run-time control of quantity without (explicit) use of `new`. Also modern C++ is smart enough to do e.g. `int x[n];` where `n` is determined at run-time, so long as you only access `x` within its declared scope. – Max May 30 '13 at 00:56
  • @Max: There are many other data structures (besides linear sequences supported by STL containers) for which it is necessary to create a run-time quantity of objects. In any case, using (or not using) STL containers is a matter of programming style, not a matter of conceptual applicability that I attempted to cover in my answer. As for `int x[n]` - it is not a part of even modern C++. It is C99, but not C++. – AnT stands with Russia May 30 '13 at 07:54
1

Considering recent C++11 and upcoming C++14 standarts, you should mostly use new operator while programming in languages with garbage collection, such a Java or C#. It is quite natural for these languages. But in modern C++ you can (and mostly always should) avoid allocating memory directly. We have a nice set of smart pointers instead now.

akalenuk
  • 3,815
  • 4
  • 34
  • 56
0

Use new when you want to allocate from the heap, not the stack. Or moving up a level of abstraction. Use new when you need the allocated memory to remain allocated after you the function (more properly scope) in which it is allocated may (in the case of threading) have exited.

tletnes
  • 1,958
  • 10
  • 30
0

You should use new when you wish an object to remain in existence until you delete it. If you do not use new then the object will be destroyed when it goes out of scope.

Some people will say that the use of new decides whether your object is on the heap or the stack, but that is only true of variables declared within functions.

Allocating (and freeing) objects with the use of 'new' is far more expensive than if they are allocated in-place so its use should be restricted to where necessary.

Tcz
  • 661
  • 5
  • 18
0

In this piece of your code you do deal with memory, but with automatic memory. The compiler sorts out for you where to store each variable. you have p1 pointing at n1 but most work was done automatically.

int *p1;
int n1 = 5;
p1 = &n1;ou

However in the next piece of code you request to dynamically allocate an int

int *p2;
p2 = new int;
*p2 = 5;

here you have created a new integer that has been stored dynamically, therefore you should also delete it otherwise you have created your first memory leak. If you allocate dynamically you have to take care you delete it after use.

delete p2;

This is the largest diference when you start to allocate memory using new do delete it otherwise the deconstrucor of an instance of an object will not run and therefore not clear the memory you have allocated.

Mahmoud Al-Qudsi
  • 28,357
  • 12
  • 85
  • 125
hetepeperfan
  • 4,292
  • 1
  • 29
  • 47
0
int * p2 = new int;

The new int part tells the program you want some new storage suitable for holding an operator uses the type to figure out how many bytes are needed. Then it finds the memory and returns the address. Next, you assign the address to p2, which is declared to be of type pointer-to-int. Now p2 is the address and *p2 is the value stored there. Compare this with assigning the address of a variable to a pointer:

int n1;
int * p1 = &n1;

In both cases (p1 and p2), you assign the address of an int to a pointer. In the second case, you can also access the int by name: p1. In the first case, your only access is via the pointer. Remember that you should use delete for freeing the memory allocated by new

delete p2;

You need to read some good books ... I think that "C++ Primer plus" is a good one for you

Az.Youness
  • 2,167
  • 1
  • 24
  • 33
  • It would be much better to link to the [master C++ book recommendation FAQ](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) instead of making your own recommendation (which happens to be a poor choice). – Ben Voigt May 29 '13 at 23:38