No New New: Raw Pointers Removed from C++

Contents[Show]

Two weeks ago, the ISO C++ standard meeting took place in Jacksonville.  Today I want to make a short detour and write about the revolutionary decision that was made in the Jacksonville meeting. Additionally, I refer to the post C++ Will no Longer Have Pointers by Fluent C++. The standard committee decided that pointers will be deprecated in C++20 and will, with a very high probability, be removed in C++23.

Honestly, what seems like a revolution is only the last step in a long evolution. First, let me explain the big picture.

 memory

The evolution of pointers in C++

Pointers have been part of C++ since the first beginning. We got them from C. From the first beginning, there was always the tendency in C++ to make the handling with pointers more type-safe without paying the extra cost.

With C++98 we got std::auto_ptr to express exclusive ownership. But std::auto_ptr had a big issue. When you copy a std::auto_ptr the resource will be moved. What looks like a copy operation was a move operation. The graphic shows the surprising behavior of a std::auto_ptr.

autoPtrCopy

This was extremely bad and the reason for many serious bugs; therefore, we got std::unique_ptr with C++11, and std::auto_ptr was deprecated in C++11 and finally removed in C++17. Additionally, we got std::shared_ptr and std::weak_ptr in C++11 for handling shared ownership. You can not copy but move a std::unique_ptr, and if you copy or assign a std::shared_ptr, the internal reference counter will be increased. Have a look here:

uniquePtrCopy

sharedPtr

Since C++11 C++ has a multithreading library, this makes the handling with std::shared_ptr quite challenging because a std::shared_ptr is per definition shared but not thread-safe. Only the control block is thread-safe but not the access to its resource. That means modifying the reference counter is an atomic operation and you have the guarantee that the resource will be deleted exactly once. This is the reason we will get C++20 atomic smart pointers: std::atomic_shared_ptr and std::atmic_weak_ptr. Read the details in the proposal: Atomic Smart Pointers.

Now to the more exciting part of C++20 and C++23. Pointers will be deprecated in C++20 and removed in C++23. Or to say it with three words: No New New (NNN).

std::unique_ptr to our rescue

But hold, we have a dogma in C++: Don't pay for anything you don't need. How can we program without a pointer? Just use an std::unique_ptr. A std::unique_ptr is by design as fast and as slim as a raw pointer but has a great benefit: it automatically manages its resource.

Only to remind you. Here is a simple performance test.

// all.cpp

#include <chrono>
#include <iostream>

static const long long numInt= 100000000;

int main(){

  auto start = std::chrono::system_clock::now();

  for ( long long i=0 ; i < numInt; ++i){
    int* tmp(new int(i));
    delete tmp;
    // std::shared_ptr<int> tmp(new int(i));
    // std::shared_ptr<int> tmp(std::make_shared<int>(i));
    // std::unique_ptr<int> tmp(new int(i));
    // std::unique_ptr<int> tmp(std::make_unique<int>(i));
  }

  std::chrono::duration<double> dur= std::chrono::system_clock::now() - start;
  std::cout << "time native: " << dur.count() << " seconds" << std::endl;

}

 

The program allocates and deletes 100.000.000 ints.  I use a raw pointer, std::shared_ptr, and std::unique_ptr in two variations. I executed the program with and without maximum optimization on Linux and Windows. Here are the numbers.

 comparisonEng

The numbers show it black on blue. The two variations of std::unique_ptr are as fast as the raw pointers on Linux and Windows. For the details of the numbers, read my previous post: Memory and Performance Overhead of Smart Pointers.

Ownership semantic

We use pointers, particularly raw pointers, far too often. The question if you should use a pointer boils down to one question: Who is the owner? Luckily, we can directly express our intention about ownership in code.

  • Local objects. The C++ runtime, as the owner, automatically manages the lifetime of these resources. The same holds for global objects or members of a class. The guidelines call them scoped objects.
  • References: I'm not the owner. I only borrowed resources that could not be empty.
  • Raw pointers: I'm not the owner. I only borrowed the resource that can be can be empty. I must not delete the resource.
  • std::unique_ptr: I'm the exclusive owner of the resource. I may explicitly release the resource.
  • std::shared_ptr: I share the resource with other shared ptr. I may explicitly release my shared ownership.
  • std::weak_ptr: I'm not the owner of the resource, but I may become temporary the shared owner of the resource by using the method std::weak_ptr::lock.

We have only to change our practice in one out of six use cases, and we are okay with the next evolution step in C++.

What's next?

Sorry for the detour, but the Jacksonville decision was worth a detour. The next post will be about the rules for performance in the C++ Core Guidelines.

Further Information

The decision to the next pdf bundle is made. It will take me about a week to prepare the pdf-bundles. First, I have to look for typos. People already subscribed to my newsletter will get them automatically.

 

 

 

 

Thanks a lot to my Patreon Supporters: Matt Braun, Roman Postanciuc, Tobias Zindl, G Prvulovic, Reinhold Dröge, Abernitzke, Frank Grimm, Sakib, Broeserl, António Pina, Sergey Agafyin, Андрей Бурмистров, Jake, GS, Lawton Shoemake, Animus24, Jozo Leko, John Breland, Venkat Nandam, Jose Francisco, Douglas Tinkham, Kuchlong Kuchlong, Robert Blanch, Truels Wissneth, Kris Kafka, Mario Luoni, Friedrich Huber, lennonli, Pramod Tikare Muralidhara, Peter Ware, Daniel Hufschläger, Alessandro Pezzato, Bob Perry, Satish Vangipuram, Andi Ireland, Richard Ohnemus, Michael Dunsky, Leo Goodstadt, John Wiederhirn, Yacob Cohen-Arazi, Florian Tischler, Robin Furness, Michael Young, Holger Detering, Bernd Mühlhaus, Matthieu Bolt, Stephen Kelley, Kyle Dean, Tusar Palauri, Dmitry Farberov, Juan Dent, George Liao, Daniel Ceperley, Jon T Hess, Stephen Totten, Wolfgang Fütterer, Matthias Grün, Phillip Diekmann, Ben Atakora, Ann Shatoff, and Rob North.

 

Thanks, in particular, to Jon Hess, Lakshman, Christian Wittenhorst, Sherhy Pyton, Dendi Suhubdy, Sudhakar Belagurusamy, Richard Sargeant, Rusty Fleming, John Nebel, Mipko, Alicja Kaminska, and Slavko Radman.

 

 

My special thanks to Embarcadero CBUIDER STUDIO FINAL ICONS 1024 Small

 

My special thanks to PVS-Studio PVC Logo

 

My special thanks to Tipi.build tipi.build logo

 

My special thanks to Take Up Code TakeUpCode 450 60

 

Seminars

I'm happy to give online seminars or face-to-face seminars worldwide. Please call me if you have any questions.

Bookable (Online)

German

Standard Seminars (English/German)

Here is a compilation of my standard seminars. These seminars are only meant to give you a first orientation.

  • C++ - The Core Language
  • C++ - The Standard Library
  • C++ - Compact
  • C++11 and C++14
  • Concurrency with Modern C++
  • Design Pattern and Architectural Pattern with C++
  • Embedded Programming with Modern C++
  • Generic Programming (Templates) with C++

New

  • Clean Code with Modern C++
  • C++20

Contact Me

Modernes C++,

RainerGrimmDunkelBlauSmall

 

Tags: Outdated

Comments   

+6 #11 Merry Poppinzz 2021-06-06 02:11
Better remove this FAKE article.
Why you keep FALSE info misleading others?
Quote
0 #12 federico.r.figueredo 2022-10-12 17:21
Please remove this misleading article to stop confusing new C++ developers. The new operator will not (and shouldn't) ever be removed from C++. They are still the way to instantiate dynamically allocated objects and, as long as you always match a new with a delete, you can use them w/o problem. They 're the equivalent to a manual transmission in a car. You want use automatic transmission? fine, you 're free to use smart pointers that 'll de-allocate memory for you.
Quote
+1 #13 Herb Gilliland 2022-10-27 13:50
This is an APRIL FOOLS PRANK
Quote
0 #14 Midwest Sensibility 2022-10-29 11:42
APRIL FOOLS PRANKs have a ONE DAY LIFESPAN. When left up beyond that they are simply disinformation, on par with "the Big Lie" of a stolen election and Holocaust denial. That's how such things start. Someone decides a prank is funny. They leave it up for maximum laughs. A quick read by anyone, less informed or not, and to them it is fact. They now go forward preaching a lie as fact.

April Fool's jokes can only be played and displayed on April first. After that they have different names, none of them good or funny.
Quote
-1 #15 Axel Schweiß 2022-12-09 19:43
You: What looks like a copy operation was actually a move operation.
Assembler Programmer: What is the Difference ?
Quote
0 #16 Midwest Sensibility 2022-12-14 19:10
http://bitsavers.informatik.uni-stuttgart.de/pdf/dec/vax/vms/2.0/AA-D033C-TE_VAX-11_2.0_Macro_Users_Guide_198003.pdf

MOVC5

The difference between a copy and a move from someone who coded Assembly.

In 3 operand format, the destination string specified by the length and destination
address operands is replaced by the source string specified by the length and
source address operands. In 5 operand format, the destination string specified
by the destination length and destination address operands is replaced by the
source string specified by the source length and source address operands. If the
destination string is longer than the source string, the highest-addressed bytes
of the destination are replaced by the fill operand. If the destination string is
shorter than the source string, the highest-addressed bytes of the source string
are not moved. The operation of the instruction is such that overlap of the source
and destination strings does not affect the result.
Quote
0 #17 Midwest Sensibility 2022-12-14 19:10
Second difference

http://bitsavers.informatik.uni-stuttgart.de/pdf/dec/vax/vms/2.0/AA-D033C-TE_VAX-11_2.0_Macro_Users_Guide_198003.pdf

You can COPY non-relocatable code anywhere you want, but you can only MOVE relocatable code within virtual memory.

====
An object module produced by VAX-11 MACRO is relocatable; that is, it
can be linked anywhere in virtual memory. The linker IDodifies
relocatable addresses so that they reflect the virtual memory
locations in which the module will run. Once linked, the image can
only be moved in virtual memory if the source code follows certain
rules concerning addressing modes and the storage of addresses.
Source code that follows these rules, and thus can be moved in virtual
memory, is called "position-independent code." Source code that does
not follow these restrictions is called "position-dependent code."
Images linked from position-dependent code will run correctly only at
one virtual memory location.

Position independence is important if you are creating a shareable
image. To use a shareable image, you must relink it with object
modules. If the shareable image is position independent, the linker
can place it anywhere in virtual memory. If the shareable image is
position dependent, the linker must place it at a fixed virtual
address. You cannot link object modules with two position-dependent,
shareable images that share a virtual address.
====
Quote

Stay Informed about my Mentoring

 

Mentoring

English Books

Course: Modern C++ Concurrency in Practice

Course: C++ Standard Library including C++14 & C++17

Course: Embedded Programming with Modern C++

Course: Generic Programming (Templates)

Course: C++ Fundamentals for Professionals

Course: The All-in-One Guide to C++20

Course: Master Software Design Patterns and Architecture in C++

Subscribe to the newsletter (+ pdf bundle)

All tags

Blog archive

Source Code

Visitors

Today 2155

Yesterday 4344

Week 39033

Month 19279

All 12097488

Currently are 178 guests and no members online

Kubik-Rubik Joomla! Extensions

Latest comments