No New New: Raw Pointers Removed from C++

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 Will no Longer Have Pointers by Fluent C++. The standard committee decided that pointers will be deprecated in C++20 and will with very high probability removed in C++23.

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

 The evolution of pointers in C++

Pointers are 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 an std::auto_ptr the resource will be moved. What looks like a copy operation was actually a move operation. The graphic shows the surprising behaviour of an std::auto_ptr.

This was extremely bad and the reason for a lot of 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 an std::unique_ptr and if you copy or assign an std::shared_ptr, the internal reference counter will be increased. Have a look here:

Since C++11 C++ has a multithreading library. This makes the handling with std::shared_ptr quite challenging because an 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 with C++20 atomic smart pointers: std::atomic_shared_ptr and std::atmic_weak_ptr. Read the details in the proposal: Atomic Smart Pointers.

Proudly powered by WordPress | Theme: Baskerville 2 by Anders Noren.

Up ↑