473,654 Members | 3,239 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Multiple calls to new in member initializer list okay?

The book "C++ Coding Standards" by Herb Sutter and Andrei Alexandrescu
warns against potential memory leaks when having multiple calls to
operator new within a single statement. (Item 13, page 25.) These
leaks would still be there when wrapping the result of each "new" in a
temporary smart pointer object.

Is there a simular risk when having multiple calls to new in member
initializer list of a constructor? For example:

class Foo
{
// I might use either std::auto_ptr or boost::scoped_p tr.
const std::auto_ptr<A > m_a;
const std::auto_ptr<B > m_b;
public:
Foo() : m_a(new A), m_b(new B) {}
};

Is the compiler allowed to do:
1. allocate memory for m_a
2. allocate memory for m_b
3. call the constructor of A
4. call the constructor of B

And then, is it allowed to leave a memory leak when the constructor of A
throws an exception?

Kind regards,

Niels Dekker
http://www.xs4all.nl/~nd/dekkerware
Jul 23 '05 #1
1 2936
Niels Dekker - no reply address wrote:
The book "C++ Coding Standards" by Herb Sutter and Andrei Alexandrescu
warns against potential memory leaks when having multiple calls to
operator new within a single statement. (Item 13, page 25.) These
leaks would still be there when wrapping the result of each "new" in a
temporary smart pointer object.

Is there a simular risk when having multiple calls to new in member
initializer list of a constructor? For example:

class Foo
{
// I might use either std::auto_ptr or boost::scoped_p tr.
const std::auto_ptr<A > m_a;
const std::auto_ptr<B > m_b;
public:
Foo() : m_a(new A), m_b(new B) {}
};

Is the compiler allowed to do:
1. allocate memory for m_a
2. allocate memory for m_b
3. call the constructor of A
4. call the constructor of B

And then, is it allowed to leave a memory leak when the constructor of A
throws an exception?

Kind regards,

Niels Dekker
http://www.xs4all.nl/~nd/dekkerware


This looks okay to me, the reason being that there is a sequence point
between "m_a(new A)" and "m_b(new B)" (that is, the first expression is
fully evaluated before the second is considered).

If the constructor of A throws an exception, "new A" will never
complete, so no memory will be leaked. If an exception is thrown after
m_a is fully constructed then the compiler will ensure that m_a is
properly destructed, so no leaks there either. The same argument
applies to B and m_b, so I would conclude that this usage is fine.

However, there is a similar usage that is not exception safe (just in
case you haven't encountered it):

Foo(std::auto_p tr a, std::auto_ptr b)
: m_a(a), m_b(b)
{}

// ...

// NOT EXCEPTION SAFE!!
Foo f(std::auto_ptr <A>(new A), std::auto_ptr<B >(new B)) ;

Here, there is NOT a sequence point between the two calls to new, so the
compiler may choose to execute "new A", then "new B", and then construct
the auto_ptr objects, but an exception thrown during "new B" would cause
the memory from "new A" to be leaked.

-Alan
Jul 23 '05 #2

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
2519
by: Jeff Massung | last post by:
I am having a syntax issue that I hope someone else here knows how to rectify... I am loading an INI file and have a simple function to load values from it. The function is overloaded with the different return types int, double or string. A structure is defined: typedef struct INI_KEY { char strCategory; char strKey;
2
3099
by: Neil Zanella | last post by:
Hello, AFAIK the only way to initialize a reference variable defined inside a class is to initialize it in an initializer list. However, when there are multiple constructors, this means that the initializer lists have to be cut and pasted from one constructor to another. This does not seem to lend itself particularly well to maintainablility. Calling a constructor from another in C++ is not legal unlike in Java. Also, functions other...
3
1600
by: santosh | last post by:
Hello, I have const member in the class. How can I initialise these. I can not initialise in constructor ,(it is giving compilation error) What is the proper way to initialise. The code is given below. Regards, santosh
2
1430
by: William Ahern | last post by:
Is the following legal, and if so is the behavior specified? struct s { int a; const char *b; }; int main(void) { struct s test = { .a = 12,
6
1522
by: Dan Huantes | last post by:
I was presented a problem today where a class had member variable that was an object of a templated class. The class wanted to instantiate the object as a private member variable and call a constructor other than the default constructor. I couldn't figure out why it wasn't working so I changed the member variable to a pointer to an object instead and intialized it in the constructor and destroyed in the destructor. It bothered me that...
4
1468
by: Ham Pastrami | last post by:
How do you initialize objects in the initializer list? Also, while this code is probably incorrect, it does compile (and execute) and I wonder what the actual result is. class Control { Point origin; public: Control(int x, int y); }
7
3730
by: Adam Nielsen | last post by:
Hi everyone, I'm having some trouble getting the correct chain of constructors to be called when creating an object at the bottom of a hierarchy. Have a look at the code below - the inheritance goes like this: Shape | +-- Ellipse | +-- Circle
3
2150
by: Bob Altman | last post by:
Hi all, If I have a class that includes an instance of a struct as a member, how do I initialize that struct? I can't find a syntax for the constructor "initializer list" that works. For example, suppose MyStruct has 3 int members. I've tried something like this: class Test {
15
7854
by: akomiakov | last post by:
Is there a technical reason why one can't initialize a cost static non- integral data member in a class?
0
8294
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8709
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8494
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
7309
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6162
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5627
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4150
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4297
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
1597
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.