473,604 Members | 2,487 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

pointer initialization in ctor

Hi,

I have a basic question regarding some legacy code I'm working with;

Basically the code looks something like this. I'd like to know if there
are any reasons why a particular approach is taken.

Given a type X we have a class something like this;

class foo
{
public:

foo (X* x)
{
m_x = new X(); /// my question is about these 2 lines.
*m_x = *x;
}

~foo()
{
delete m_x;
}

protected:

X* m_x;

};

Now in the foo ctor above, I would have personally done something like;

foo(X* x)
{
m_x = new X(*x);
}

thereby avoiding the overhead of the default ctor call and then the
assignment, we would just use the copy ctor.

I am asking this question in the context of memory leaks. There's
nothing wrong, in the non-purist sense of the word, with the original
code. I mean it's not as efficient as it could be but it doesn't leak
and it does add memory resource concerns to the class, does it?
thanks and have a nice day

Graham
thanks and have a nice day

G

Dec 8 '05 #1
5 1613
* Gr*****@nospam. com:

I have a basic question regarding some legacy code I'm working with;
[snip] class foo
{
public:

foo (X* x)
{
m_x = new X(); /// my question is about these 2 lines.
*m_x = *x;
}

~foo()
{
delete m_x;
}

protected:

X* m_x;

};

Now in the foo ctor above, I would have personally done something like;

foo(X* x)
{
m_x = new X(*x);
}

thereby avoiding the overhead of the default ctor call and then the
assignment, we would just use the copy ctor.
There's probably no other reason than that the programmer didn't understand
constructors.

I am asking this question in the context of memory leaks. There's
nothing wrong, in the non-purist sense of the word, with the original
code. I mean it's not as efficient as it could be
Nope; unless there is some compelling reason to use dynamic allocation
the X object should just be a direct member, not accessed via a pointer.

but it doesn't leak
and it does add memory resource concerns to the class, does it?


To avoid dangling pointers the class needs a user-defined copy constructor
and an assignment operator, or alternatively, disabling these operations, or,
replace the raw pointer member with a smart pointer.

--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Dec 8 '05 #2
Gr*****@nospam. com wrote:
Hi,

I have a basic question regarding some legacy code I'm working with;

Basically the code looks something like this. I'd like to know if there
are any reasons why a particular approach is taken.

Given a type X we have a class something like this;

class foo
{
public:

foo (X* x)
{
m_x = new X(); /// my question is about these 2 lines.
*m_x = *x;
}

~foo()
{
delete m_x;
}

protected:

X* m_x;

};

Now in the foo ctor above, I would have personally done something like;

foo(X* x)
{
m_x = new X(*x);
}

thereby avoiding the overhead of the default ctor call and then the
assignment, we would just use the copy ctor.
I would go for initialization:

foo ( X* x )
: m_x ( new X ( *x ) )
{}

I am asking this question in the context of memory leaks. There's
nothing wrong, in the non-purist sense of the word, with the original
code. I mean it's not as efficient as it could be but it doesn't leak
and it does add memory resource concerns to the class, does it?


Well, it could leak. Look at the code:

m_x = new X(); // line 1
*m_x = *x; // line 2

Now, if the assignment in line 2 throws an exception, the m_x pointer will
not be deleted since (I might be wrong and I am too lazy to check the
standard right now) the destructor will not be called upon disposal of a
not completely constructed object but only the destructors for the already
constructed members. Thus, when a constructor throws, it has to clean up
the mess by itself.
Best

Kai-Uwe Bux
Dec 8 '05 #3
On Thu, 08 Dec 2005 06:40:54 -0500, Kai-Uwe Bux <jk********@gmx .net>
wrote:
Well, it could leak. Look at the code:

m_x = new X(); // line 1
*m_x = *x; // line 2

Now, if the assignment in line 2 throws an exception, the m_x pointer will
not be deleted since (I might be wrong and I am too lazy to check the
standard right now) the destructor will not be called upon disposal of a
not completely constructed object but only the destructors for the already
constructed members. Thus, when a constructor throws, it has to clean up
the mess by itself.


You are quite correct.

--
Bob Hairgrove
No**********@Ho me.com
Dec 8 '05 #4

Bob Hairgrove wrote:
On Thu, 08 Dec 2005 06:40:54 -0500, Kai-Uwe Bux <jk********@gmx .net>
wrote:
Well, it could leak. Look at the code:

m_x = new X(); // line 1
*m_x = *x; // line 2

Now, if the assignment in line 2 throws an exception, the m_x pointer will
not be deleted since (I might be wrong and I am too lazy to check the
standard right now) the destructor will not be called upon disposal of a
not completely constructed object but only the destructors for the already
constructed members. Thus, when a constructor throws, it has to clean up
the mess by itself.


You are quite correct.


And that's where Alf's suggestion of using a smart pointer becomes not
just a good idea but an absolute necessity to avoid memory leaks. (Of
course, using a non-pointer member of type X would also do the trick.)

Cheers! --M

Dec 8 '05 #5
mlimber wrote:

Bob Hairgrove wrote:
On Thu, 08 Dec 2005 06:40:54 -0500, Kai-Uwe Bux <jk********@gmx .net>
wrote:
>Well, it could leak. Look at the code:
>
> m_x = new X(); // line 1
> *m_x = *x; // line 2
>
>Now, if the assignment in line 2 throws an exception, the m_x pointer
>will not be deleted since (I might be wrong and I am too lazy to check
>the standard right now) the destructor will not be called upon disposal
>of a not completely constructed object but only the destructors for the
>already constructed members. Thus, when a constructor throws, it has to
>clean up the mess by itself.


You are quite correct.


And that's where Alf's suggestion of using a smart pointer becomes not
just a good idea but an absolute necessity to avoid memory leaks.


Actually this is not *where* smart pointers become a necessity. The
constructor

foo ( X* x )
: m_x ( new X ( *x ) )
{}

is exception safe whether m_x is a smart or a dumb pointer. Life (aside from
the operator= and copy constructor issues) becomes tricky, when you have
*two* members that might throw:

foo ( whatever )
: m_ptr_one ( new X ( something ) )
, m_ptr_two ( new Y ( something_else ) ) // bad line
{}

will leak m_ptr_one if the bad line throws.
However, it might be worthwile to note that an innocent looking line like

*ptr = some_value;

may throw and can leak memory if the pointer object ptr is destroyed during
stack unwinding.
Anyway, I am with you folks that raw pointers should not rear their ugly
head into code without reason.
Best

Kai-Uwe Bux
Dec 8 '05 #6

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

Similar topics

5
9450
by: Michael McKnerney | last post by:
Hi, It seems I can influence how a base class is initialized beyond the 'normal' manner and I was wondering if someone can tell me why this. Here's my example. class A { public: A(int a=1, int b=1, int c=1) : _a(a), _b(b), _c(c) {}
4
2130
by: Carsten Spieß | last post by:
Hello all, i have a problem with a template constructor I reduced my code to the following (compiled with gcc 2.7.2) to show my problem: // a base class class Base{}; // two derived classes
5
3021
by: PasalicZaharije | last post by:
Hallo, few days ago I see ctor like this: Ctor() try : v1(0) { // some code } catch(...) { // some code }
7
1396
by: manuhack | last post by:
In Chapter 6 of Eckel's thinking in C++, there is an example: //: C06:Stack3.h // With constructors/destructors #ifndef STACK3_H #define STACK3_H class Stack { struct Link {
5
1688
by: nagrik | last post by:
Hello group, Last week I picked up a thread, which pointed out that if a copy constructor is created with pointers instead of reference, there is a danger of it going in infinite recursion. My observation: 1. Compiler does not complain.
14
1869
by: Glen Dayton | last post by:
While looking at some old code I ran across a snippet that increments a pointer to access different members of a structure: .... struct Badness { std::string m_begin; std::string m_param1; std::string m_param2; std::string m_end;
12
5195
by: Henrik Goldman | last post by:
Hi, I have some data which is stored as plain old C structures. Until now I've had arrays of these structs on stack but due to stack overrun I need to move these to heap. I've been trying out some smart pointers to help but so far the implementation I've been dealing with has had problems with operator since it could conflict when using the same class with "unsigned char". Do you have any recommendations for smart pointers able to...
18
9105
by: Ehud Shapira | last post by:
Is it possible to have a declaration of a struct pointer initialized to an unnamed struct? (I'm only concerned with static/global variables, if it matters.) I'm trying to do something like: struct st_a { int i, j; };
11
2397
by: subramanian100in | last post by:
Suppose we have a class named Test. Test obj; // assuming default ctor is available Test direct_init(obj); // direct initialization happens here Test copy_init = obj; // copy initialization happens here Suppose we have a function void fn(Test arg);
0
7929
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
8419
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8409
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
8065
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
8280
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6739
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
5882
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
5441
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();...
1
2434
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

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.