Running a project in C ++. Should I worry about freeing dynamically allocated memory?

I'm pretty good at C, and freeing up memory in C is a must.

However, I am starting my first C ++ project, and I have heard some things about how you do not need to free up memory using common pointers and other things.

Where should I read about this? Is this a valuable replacement for the correct delete C ++ functionality? How it works?

EDIT

I am confused, some people say that I have to highlight with new and use smart pointers for the release process.

Other people say that I should not allocate dynamic memory in the first place.

Others say that if I use a new one , I also need to use delete , like C.

So, which method is considered more standard and more commonly used?

+4
source share
14 answers

Where should I read about this?

Herb Sutter Exceptional C ++ and Scott Meyers More Effective C ++ are excellent books that detail the subject.

There is also a lot of discussion on the Internet (a Google search or StackOverflow for “RAII” or “smart pointer” will certainly bring a lot of good results).

Is this a valuable replacement for the correct delete C ++ functionality?

That's right. The ability to not worry about cleaning up resources, especially when an exception is thrown, is one of the most valuable aspects of using RAII and smart pointers.

+18
source

What I had in mind in my comment (sorry for being brief - I had to rush out to the stores) is what you should use:

 std::string s = "foobar"; 

but not:

 std::string * s = new std::string( "foobar" ); ... delete s; 

and

 vector <Person> p; p.push_back( Person( "fred" ) ); 

but not:

 vector <Person *> p; p.push_back( new Person( "fred" ) ); 

You should always use classes that manage memory for you. In C ++, the main reason for creating an object using the new one is that you do not know its type at compile time. If this is not the case, think for a long time before using new and deleting, or even smart pointers.

+9
source

If you assign dynamic memory (with new), you need to free it (with deletion), just like using malloc / free in C. The power of C ++ is that it gives you many ways to NOT call new, in in this case you do not need to call delete.

+5
source

You still need to worry about freeing memory in C ++, just for this there are better methods / tools. It can be argued that attention to memory management in C ++ is also difficult due to the additional requirement of writing exception exception code. It does things like:

 MyClass *y = new MyClass; doSomething(y); delete y; 

Take a look completely harmless until you find that doSomething() throws an exception, and now you have a memory leak. This becomes even more dangerous as the code is supported, as the code above can be safe before someone changes the doSomething() function in a later version.

Following the RAII methodology, this is most of the trouble resolving memory management issues and using auto_ptr or generic pointers provided by libraries such as Boost to make it easier to incorporate these methods into your code.

Note that auto_ptr not a "generic" pointer. This is an object that takes responsibility for a dynamically allocated object and gives ownership of the assignment and copy. It does not consider memory references. This makes it unsuitable for use in standard containers, and many generally prefer shared_ptr boost for auto_ptr provided by the standard.

Unable to include auto_ptrs in standard containers. Some people say that their compiler and library compiles this fine, while others will tell you that they saw exactly this example recommended in the documentation of a certain popular compiler; do not listen to them.

The problem is that auto_ptr does not quite meet the requirements of the type you can put in containers, because copies of auto_ptrs are not equivalent. Firstly, there is nothing that says that the vector cannot just decide to go up and do the "extra", the internal copy of any object contains. For another, when you call generic functions that will copy elements, such as sort (), the functions should be able to assume that the copies will be equivalent. At least one popular view internally takes a copy of the "rod" element, and if you try to do this work on auto_ptrs, it will be a fun copy of the pivot auto-update object (thus taking responsibility and this is in temporary auto_ptr on the side), do the rest your work on the sequence (including copies of the unauthorized auto_ptr that was selected as the aggregate value), and when the sort is above the rod, destroyed, and you have a problem: at least one auto_ptr in the sequence (The one that led cause of the rotation) no longer owns the pointer, which he once held, and is actually a pointer, which he has already been deleted!

Taken From: Using auto_ptr Effectively

+4
source

Well of course you need to delete. I would rephrase it as "what libraries can I use that can automate the deletion of allocated memory?". I recommend that you start by reading the Boost Smart pointers page .

+2
source

The best answer I can give you is to need to call delete for every object created by a new one. Regardless of whether you do this manually or use a smart pointer based on a region or a smart pointer with reference counting or even a non-deterministic garbage collector, it still needs to be done.

Having said that, I did not manually trigger the deletion after 10 years or so. Whenever I can create an automatic object (on the stack); when I need to create an object on the heap for some reason, I try to use a smart pointer based on a region, and in rare cases when there is a legitimate reason for sharing, I use a smart pointer with reference counting.

+2
source

This is a great question, and actually a few in one:

Do I have to worry about memory management?

Yes! In C ++ there is no garbage collection. Each time you select something with new , you need to either call delete in your own code, or delegate this responsibility to something like a smart pointer .

When should you use dynamic memory allocation?

The reasons why you want to use dynamic memory allocation (allocation with new ). Some of them include:

  • You do not know the size of the thing that you allocate at compile time.
  • You do not know the type of thing that you select at compile time.
  • You reuse the same data in different contexts and do not want to pay the performance overhead when copying this data.

There are many other reasons, and they are crude in generalizations, but you get the idea.

What tools can I use to manage memory?

Smart pointers are the way here. The smart pointer will take responsibility for the allocated memory and then automatically free this memory at a specific time, depending on the smart pointer policy.

For example, boost :: scoped_ptr will free up memory for you when it goes out of scope

 { scoped_ptr<MyClass> myVar( new MyClass() ); // do Something with myVar } // myVar goes out of scope and calls delete on its MyClass 

In general, you should use smart pointers over raw pointers at any time. This will save you years of tracking memory leaks.

Smart pointers come in many forms, including:

If you can use Boost smart pointers, I would do it. They are rock!

+2
source

Freeing up memory in C ++ is just as necessary as in C.

What you might think of is an intelligent pointer library (the standard auto_ptr library among others) that will do reference counting for you.

+1
source

Since C ++ does not have a garbage collector built into the language, you need to know what memory you allocate dynamically and how this memory is freed.

However, you can use smart pointers to alleviate the need to manually free memory through delete - for example, see Smart Ponters (boost) .

+1
source

First of all, before you start using auto_ptr and write your own RAII classes, learn how to use the standard template library. It provides many common container classes that automatically allocate their internal memory when you create them and free them when they go out of scope - things like vectors, lists, maps, etc. When you use STL, using the new operator and deleting (or malloc and free) are rarely necessary.

+1
source

'confused, some say that I should highlight using new and use smart pointers for the release process.

They are right. As in C, you still need to manage all your memory anyway. however, there are ways to use the language to automate deletion.

Smart pointers are basically local area wrappers for pointers that use the .dtor object to remove the corresponding pointer when a smart pointer that looks like any other object on the stack exits the area

0
source

The beauty of C ++ is that you have explicit control over when things are created and when things are destroyed. Do it right and you won’t have problems with memory leaks, etc.

Depending on your environment, you can create objects on the stack, or you may want to dynamically allocate (to create them on the heap, "heap" is a heap in quotation marks, because this is an excessive term, but so far good enough).

Foo x; // created on the stack - is automatically destroyed when the program exits from this block of code in which it was created.

Foo * y = new Foo; // created on the heap - its OK to go through this round, since you control its destroyed

Whenever you use the "new", you should use the appropriate version of the uninstall ... somewhere, somehow. If you use new to initialize a smart pointer, for example:

std :: auto_ptr x = new Foo;

In fact, you are creating two elements. The auto_ptr instance and the Foo instance. auto_ptr is created on the stack, Foo on the heap.

When the stack is "unwound", it is automatically called delete in this instance of Foo. Automatic cleaning for you.

So, as a general rule, use the stack version whenever possible / practical. In most cases, it will be faster.

0
source

In order of preference, you should:

  • Avoid handling the distribution yourself. C ++ STL (Standard Template Library) comes with a lot of containers that handle the selection for you. Use vector instead of dynamically allocated arrays. Use string instead of char * for character arrays. Try to find the appropriate container from the STL, and not create your own.

  • If you are developing your own class and, frankly, need dynamic allocation (and usually will not, if you compose your class using STL members), put all instances of new ( new[] ) in your constructor and all instances of delete ( delete[] ) in your destructor. You do not need malloc and free , as a rule.

  • If you cannot keep your distributions paired inside constructors and destructors, use smart pointers. This is actually not so different from # 2; smart pointers are basically just special classes that use destructors to provide release.

0
source

Source: https://habr.com/ru/post/1308165/


All Articles