

Initialization list exceptions and raw pointers
source link: https://vorbrodt.blog/2019/04/03/initialization-list-exceptions-and-raw-pointers/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Initialization list exceptions and raw pointers
What to do when an exception is thrown on the initialization list when allocating memory for a raw pointer? The situation is easy if your class only has one raw pointer member, but it gets complicated with two or more. Here’s a code example that’s guaranteed to leak memory if the second new int throws an exception (because the destructor will not be called):
There is no way to free the memory allocated to p1 if p2(new int) throws! Let’s build on my previous example and see what happens if we use a function try-catch block on the constructor:
Still no good! Because accessing p1 and p2 in the catch block leads to undefined behavior. See here.
The only way to guarantee correct behavior is to use smart pointers. This works because 1) the initialization list allocates in pre-defined order (the order of member declaration) and 2) the destructors of already created members will be called. Here’s the correct way of allocating multiple pointers:
This is guaranteed to do proper cleanup if the second
make_unique<int>() throws
std::bad_alloc
Complete listing (bad_pointer.cpp):
Recommend
-
23
C++ Can't Abandon Raw Pointers Feb 27, 2018 …yet This post was born from
-
11
Package initialization and program execution order yourbasic.org/golang Basics F...
-
15
Objective-C Class Loading and Initializationmikeash.com: just this guy, you know? Friday Q&A 2009-05-22: Objective-C Class Loading and Initialization by Mi...
-
16
译文:DDR4 - Initialization, Training and CalibrationljgibbsIC 前端工程师 / 业余 FPGA,计组爱好者
-
26
Raw Pointers in Unsafe Rust are quite powerful Knoldus Blog Audio Reading Time: 4 mi...
-
26
Microsoft unveils C# 11 list patterns, raw string literals Next version of Microsoft’s flagship programming language for .NET development will also simplify the synt...
-
12
Introduction In many C++ programs, the main function #includes the world and utterly lacks structure. This article describes how to initialize a system in a structured manner. It then discusses how to evolv...
-
12
Arrays in the initialization list of a constructor advertisements I'm trying to figure out how to declare an array of an arbitra...
-
8
Initialization and Validation Webhooks in Operators When developing custom Kubernetes resources, static defaults and simple validations for resource properties can be defined in OpenAPI/JSON s...
-
12
Dominik Tylczynski November 15, 2022 1 minu...
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK