Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use of raw pointers in modern C++ post C++11 [closed]

What are some of the main reasons to use raw pointers in 2014, given that the C++11 standard is now well supported by most decent compilers?

I identified a couple of scenarios :

  1. You are extending a legacy codebase that makes heavy use of raw pointers, and you would like to maintain consistency in style.

  2. You are using a library that only exports raw pointers, but I guess you could still make use of casts.

  3. You want to exploit pointers's capability to provide multiple levels of indirection. (I do not know C++11 well enough to know if this can be achieved using smart pointers, or using some other techniques.)

What other scenarios do you think are appropriate for use of pointers?

Would you even recommending learning about pointers in general, today?

like image 686
Gumbly jr. Avatar asked Sep 06 '14 22:09

Gumbly jr.


People also ask

When would you use a raw pointer?

Pointers (along with references) are used extensively in C++ to pass larger objects to and from functions. It's often more efficient to copy an object's address than to copy the entire object. When defining a function, specify pointer parameters as const unless you intend the function to modify the object.

Why do we need raw pointers in smart pointers?

Smart pointers are class objects that behave like raw pointers but manage objects that are new and when or whether to delete them— smart pointers automatically delete the managed object at the appropriate time.

Are pointers used in modern C++?

In modern C++ programming, the Standard Library includes smart pointers, which are used to help ensure that programs are free of memory and resource leaks and are exception-safe.

What are raw pointers?

The raw pointers are exactly the same with normal pointers, they can be written like this: type * pointer_name = & variable_name; Since C++11, we have some special pointers, called "smart pointers". They are called "smart" because they know when they have to delete the used memory.


1 Answers

I can imagine circumstances where you have a statically-allocated array and you want to use a raw pointer to iterate through it in high-performance code. There's still nothing wrong with this.

Your #1 is true.

Your #2 is possibly not right: if you're "making use of casts" to transform raw pointers owned by a third-party library, into smart pointers (implying local ownership) then something has gone horribly wrong.

Your #3 is technically true but avoid this whenever you can.

What is not recommended nowadays is playing with raw pointers to your own, dynamically-allocated memory. That is, the advice is to avoid new without smart pointers (and the corollary is that you shouldn't need delete).

like image 114
Lightness Races in Orbit Avatar answered Sep 28 '22 20:09

Lightness Races in Orbit