Accelerated C ++: can I replace the original pointers with smart pointers?

I like this book, unfortunately, it does not cover smart pointers, because then they were not part of the standard. So, when reading a book, can I replace all the mentioned pointers with a smart pointer, referring accordingly?

+4
source share
3 answers

Well, there are different types of smart pointers. For instance:

You can create a scoped_ptr class that would be useful when distributing for a task in a block of code, and you want the resource to be automatically freed when the scope starts.

Sort of:

 template <typename T> class scoped_ptr { public: scoped_ptr(T* p = 0) : mPtr(p) {} ~scoped_ptr() { delete mPtr; } //... }; 

In addition, you can create shared_ptr , which acts the same but retains the number of links. When the number of links reaches 0, you will free.

shared_ptr will be useful for pointers stored in STL containers, etc.

So yes, you could use smart pointers for most of your program's purposes. But wisely think about which smart pointer you need and why.

Don't just โ€œfind and replaceโ€ all the pointers you come across.

+2
source

A smart pointer is a bit wrong. The "smart" part is that they will do something for you or not, they want or even understand what these things are. And this is really important. Because sometimes you want to go to the store, and smart signs will lead you to church . Smart pointers solve some very specific problems. Many argue that if you think you need smart pointers, then you are probably solving the wrong problem . I personally try not to take sides. Instead, I use the tool metaphor โ€” you really need to understand the problem you are solving and the tools that you have at your disposal. Only then can you remotely select the right tool for the job. Good luck and continue the interrogation!

+4
source

No.

Pointers that represent ownership of an object should be replaced by smart pointers.

Other pointers should be replaced with iterators (in the simplest case, this is just a typedef for the raw pointer, but no one will think that they need to be removed).

And of course, implementation code for smart pointers and iterators will still need raw pointers.

+2
source

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


All Articles