Why is it a bad idea to use the “new”?

Possible duplicate:
In C ++, why should new be used as little as possible?

Is it really a bad idea to use the “new” in instantiating a class in C ++? Found here .

I understand that using raw pointers is not recommended, but why do they have a “new” keyword in general when it's such a bad practice? Or that?

+4
source share
7 answers

The fact is that new , like pregnancy, creates a resource that is managed manually (i.e. by you), and as such it is responsible.

C ++ is a language for writing libraries, and anytime you see responsibility, the “C ++” approach is to write a library element that handles this, and that’s just that, responsibility. For dynamic memory allocation, these library components already exist and are generally referred to as smart pointers; you need to look at std::unique_ptr and std::shared_ptr (or their TR1 or Boost equivalents).

When writing blocks with one responsibility, you really need to say new and delete . But you do it once, and you think carefully about it and make sure that you provide the correct semantics for copying, assigning, and destroying. (From the point of view of exception safety, one responsibility is crucial since handling more than one single resource at a time is terribly immodest.)

After you put everything into suitable building blocks, you compose these blocks into larger and larger code systems, but in this case you no longer need to carry out any responsibility for the leadership, since the building blocks already do this for you.

Since the standard library offers resource management classes for the vast majority of use cases (dynamic arrays, smart pointers, file descriptors, strings), the fact is that a well-designed and created C ++ project should have very little need for any kind of manual resource management which includes the use of new . All objects of your handler are either automatic (regions) or members of other classes, instances of which are in turn covered or managed by someone.

Given this, the only time you should say new is when you create a new resource management object; although even then this is not always necessary:

 std::unique_ptr<Foo> p1(new Foo(1, 'a', -2.5)); // unique pointer std::shared_ptr<Foo> p2(new Foo(1, 'a', -2.5)); // shared pointer auto p3 = std::make_shared<Foo>(1, 'a', -2.5); // equivalent to p2, but better 

Update: I think I could solve only half the problems with the OP. Many people coming from other languages ​​have the impression that any object should be created with the expression new -type. This in itself is very useless thinking when approaching C ++:

The most important difference in C ++ is the lifetime object, or "storage class." It can be one of the following: automatic (copied), static (permanent) or dynamic (manual). Global variables have a static lifetime. The vast majority of all variables (declared as Foo x; inside the local scope) have an automatic lifetime. For dynamic storage only, we use the expression new . The most important thing to understand when you come to C ++ from another OO language is that most objects only need battery life, and therefore there is never anything to worry about.

So, the first implementation should be that "C ++ rarely requires dynamic storage." I feel that this may have been part of the OP question. The question may have been better worded as "Is it really a bad idea to dynamically allocate objects?" Only after you decide that you really need a dynamic repository, which we get before actually discussing whether to say a lot of new and delete , or if there are preferred alternatives, which is the point of my original answer.

+13
source

Avoiding new as much as possible means many benefits, such as:

  • First of all, you also avoid delete . Smart pointers can help here. So this is not so.

  • You avoid rule three (in C ++ 03) or rule five (in C ++ 11). If you use new when developing a class, that is, when your class manages the raw memory inside, you probably have to consider this rule.

  • It is easy to implement exclusive code if you are not using new . Otherwise, you will have to face many problems making your code safe.

Using new unnecessarily means that you are causing problems. I saw when an inexperienced programmer uses new , he often has better alternatives, such as standard use containers and algorithms. Using standard containers avoids most of the problems associated with explicitly using new .

+3
source

Not bad, but everything that you allocate with new should be freed with delete . This is not always trivial, especially considering the exceptions. I think this is what this message meant.

+2
source

This is not a “bad idea to use new ones” - the poster incorrectly ruined his business. Rather, using new ones does not give you two different things.

new provides a new, separately allocated instance of the class and returns a pointer to this instance.

Using the class name without new creates an automatic instance of the class that will go "poof" when it goes out of scope. This "returns" the instance itself, not the pointer (and therefore the syntax error in this other thread).

If you use new in the reference case and add * to pass the compiler, this will leak the object. If, on the other hand, you passed a parameter to a method that was going to store it somewhere, and you passed a non-new instance, forcing it to work with & , you would end up saving the dangling pointer.

0
source

new that you delete , and free that you are malloc (do not mix them, you will be in trouble). Sometimes you have to use new ones, because the data selected with the new one will not fall out of scope ... if the data pointer is not lost, and this is a problem with new . But this is a mistake on the side of the programmer, not a keyword.

0
source

It depends on what the code needs. This is the answer you are referring to, the vector contains client instances, not pointers to client instances.

In C ++, you can create an object directly on the stack without using new ones, for example, V1 and V2 in the code below:

 void someFct() { std::vector<client> V1; //.... std::vector<client*> V2; } 

When using V2, you will need to create a new client instance with a new operation, but client objects will not be released (deleted) when V2 goes beyond. There is no garbage collector. You must delete the objects before leaving the function.

To automatically create instantiated instances, you can use std :: shared_ptr. This makes the code a little longer for writing, but it is easier to maintain in the long run:

 void someFct() { typedef std::shared_ptr<client> client_ptr; typedef std::vector<client_ptr> client_array; client_array V2; V2.push_back(client_ptr(new client())); // The client instance are now automatically released when the function ends, // even if an exception is thrown. } 
0
source

Is it really a bad idea to use the “new” in instantiating a class in C ++?

Its often bad because it is not needed, and the code becomes much easier when you do not use it falsely. In cases where you can leave without using it, do it. Ive written entire libraries, more than once using new .

I understand that using raw pointers is not recommended, but why do they have a “new” keyword in general when it's such a bad practice? Or that?

This is not universally bad, just unnecessary most of the time. But there are also times when it comes up, and therefore there is such a keyword. However, C ++ could leave without a keyword, because new combines two concepts: 1. it allocates memory, and 2. it initializes memory for the object.

You can separate these processes using other methods of allocating memory, and then calling the constructor ("placing new"). This is actually done everywhere, for example, the standard library, through allocators.

On the other hand, rarely (read: never) it makes sense for client code to manage uninitialized memory, so it makes sense not to decouple these two processes. Therefore, the existence of new .

-1
source

All Articles