473,606 Members | 2,171 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Do i need a copy contructor?

Hi,

if I have a structure like...

struct sMyPointers{
ClassA *m_pPointerA;
ClassB *m_pPointerB;
void *m_pPointerToSo methingElse;
};

And then

std::vector<sMy Pointers *> pPointers;

sMyPointers *pA = new sMyPointers();
pPointers->push_back(pA );
pA = new sMyPointers();
pPointers->push_back(pA );
pA = new sMyPointers();
pPointers->push_back(pA );

The reason why I want pointers is mainly or speed but also to make sure that
I only have one set of data, rather than a bunch of copies all over the
place.
The data is created one and deleted once.

But is the above correct? Is it good coding practice?

regards.
Simon
Jul 23 '05 #1
9 2833
"Simon" <sp********@exa mple.com> schrieb:
struct sMyPointers{
ClassA *m_pPointerA;
ClassB *m_pPointerB;
void *m_pPointerToSo methingElse;
};
Where is the initialization of the pointers done? And especially:
where are the pointers deleted? Do you have a destructor doing this?
This question is relevant for answering on "Do I need a copy
constructor?" If these instances of sMyPointers own the inner
pointers, I would suggest to make a copy constructor.
std::vector<sMy Pointers *> pPointers;

sMyPointers *pA = new sMyPointers();
pPointers->push_back(pA );
pA = new sMyPointers();
pPointers->push_back(pA );
pA = new sMyPointers();
pPointers->push_back(pA );
This is legal. You could avoid the variable pA. You do not need a copy
constructor here.
The reason why I want pointers is mainly or speed but also to make
sure that I only have one set of data, rather than a bunch of copies
all over the place. The data is created one and deleted once.

But is the above correct? Is it good coding practice?


Notice, the allocation and deallocation of objects on the heap can
take more time than to make a copy. It depends on the objects and
their data.

T.M.
Jul 23 '05 #2
Simon wrote:
struct sMyPointers{
ClassA *m_pPointerA;
ClassB *m_pPointerB;
void *m_pPointerToSo methingElse;
};


The real question is "Who owns the resources that the pointers points
to?"

Is this struct just a "holder" for grouping three pieces of data
together, or is it actually responsible for managing the resources? In
general, whichever class does the actual resource management should
have a copy constructor, destructor, and assignment operator.

Technically, this struct is okay for use in standard containers, but if
you want your code to be reliable you really have to answer the above
questions.

Jul 23 '05 #3
> Simon wrote:
struct sMyPointers{
ClassA *m_pPointerA;
ClassB *m_pPointerB;
void *m_pPointerToSo methingElse;
};


The real question is "Who owns the resources that the pointers points
to?"

Is this struct just a "holder" for grouping three pieces of data
together, or is it actually responsible for managing the resources? In
general, whichever class does the actual resource management should
have a copy constructor, destructor, and assignment operator.

Technically, this struct is okay for use in standard containers, but if
you want your code to be reliable you really have to answer the above
questions.


Well my class is in charge of the pointers, so it will create them and
delete them as needed.
The idea was to 'tidy' the code a little, rather than having

The number of items in the vector is unknown, so it is nice to be able to
create them on the fly and just add them to a structure.
That way I can manage the data better.

By having the structure, (and then the vector), the number of items is
immaterial.
I can create 5, 10, 100 instances as long as I delete every single items.

Simon.


Jul 23 '05 #4
> Well my class is in charge of the pointers, so it will create them and
delete them as needed.
The idea was to 'tidy' the code a little, rather than having

The number of items in the vector is unknown, so it is nice to be able to
create them on the fly and just add them to a structure.
That way I can manage the data better.

By having the structure, (and then the vector), the number of items is
immaterial.
I can create 5, 10, 100 instances as long as I delete every single items.


Imagine this:

class C
{
private:
int *i;

public:
C()
: i(new int)
{
}

~C()
{
delete i;
}
};

int main()
{
C c1;
C c2(c1);

// here, both c1 and c2 have their pointer 'i' pointing to the same
// int
}

When c2 goes out of scope, it deletes its int. Then c1 goes out of
scope and the deletes the very same one, which is undefined behavior.

When a class manages memory, it usually needs a copy constructor and an
assignment operator:

class C
{
private:
int *i;

public:
C()
: i(new int)
{
}

C(const C &c)
: i(new int(c.i))
{
}

C &operator=(cons t C &c)
{
delete i;
i = new int(c.i);
}

~C()
{
delete i;
}
};

But you'd be better with a kind of smart pointer, which manages this
automatically. std::auto_ptr does not.
Jonathan

Jul 23 '05 #5
Just wanted to know if you were paying attention... The second code
should be

class C
{
private:
int *i;

public:
C()
: i(new int)
{
}

C(const C &c)
: i(new int(*c.i))
{
}

C &operator=(cons t C &c)
{
delete i;
i = new int(*c.i);

return *this;
}

~C()
{
delete i;
}
};
Jonathan

Jul 23 '05 #6
Just wanted to know if you were paying attention... The second code
should be


Thanks, I didn't want to say anything.

but while we are on the subject, isn't

const C &operator=(cons t C &c)
....

better than

C &operator=(cons t C &c)
?

Simon
Jul 23 '05 #7
On 2005-07-15 07:30:10 -0400, "Simon" <sp********@exa mple.com> said:
Just wanted to know if you were paying attention... The second code
should be


Thanks, I didn't want to say anything.

but while we are on the subject, isn't

const C &operator=(cons t C &c)
...

better than

C &operator=(cons t C &c)


No, why do you think it would be? Generally, when overloading
operators, a good goal is to make them behave as closely as possible to
how they would behave when applied to built-in types; using the
assignment operator on a built in type results in what is essentially a
non-const reference to the left operand:

int i;
int &ir = i = 5; //Assigns 5 to i, and binds ir to i
--
Clark S. Cox, III
cl*******@gmail .com

Jul 23 '05 #8
>>
Just wanted to know if you were paying attention... The second code
should be


Thanks, I didn't want to say anything.

but while we are on the subject, isn't

const C &operator=(cons t C &c)
...

better than

C &operator=(cons t C &c)


No, why do you think it would be? Generally, when overloading operators, a
good goal is to make them behave as closely as possible to how they would
behave when applied to built-in types; using the assignment operator on a
built in type results in what is essentially a non-const reference to the
left operand:

int i;
int &ir = i = 5; //Assigns 5 to i, and binds ir to i


Truth be told, I am not sure, I remember reading somewhere that it was
better to do the "const", but I don't know where I got such an idea from.

Maybe someone could help me on that one.

Simon
Jul 23 '05 #9
> Truth be told, I am not sure, I remember reading somewhere that it was
better to do the "const", but I don't know where I got such an idea from.

Maybe someone could help me on that one.


Well for myself, I remember reading that void main() was better, so you
can't count on that.

An argument you may have heard is that it allows

(c1=c2) = c3;

which looks weird, but is allowed for ints:

int i1=1, i2=2, i3=3;

(i1=i2)=i3;

As our good Scott Meyers said, "do as the ints do".

Jonathan

Jul 23 '05 #10

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

Similar topics

2
4606
by: Ishira | last post by:
Hello, Please help. I am seriously at my wits end. Just when I feel I have completely understood copy contructor, I am stumped yet again. I have a class which has a CARRAY of objects. I am trying to write a copy constructor for the class and it's simply havoc! The array variable is private to the class and simply contains objects without
4
3369
by: Matthias Spiller | last post by:
Hi, following problem. I'm writing an Image class and want to use templates: .... template<class TType, int TLayers> class Image { public: Image();
2
1872
by: | last post by:
I have the some HTML and JavaScript code that implements a type-ahead capability for a text input control linked to a select control (see end of message). The type-ahead functionality works well. The only problem is that I'd like to implement an external event sink so that when the text control loses focus, I can do ... well whatever I might happen to want the event sink to do. The code below will even sink the onblur event of the...
2
480
by: Bruno Ripa | last post by:
Hallo, imagine to have the following simple code: #include <iostream> class C { public: C() {}
6
2405
by: nutty | last post by:
Hi all, I have the following problem ( explanation below code ): // main.cpp class noncopyable { protected: noncopyable() {}
15
16293
by: Brett Wickard | last post by:
Ok, this should be simple, but how do I copy a reference type by value? Meaning SomeComplexObject s1 = new SomeComplexObject (); SomeComplexObject s2 = new SomeComplexObject (); s1.color = "red"; s2 = s1; s2.color = "blue";
15
3814
by: Frederick Gotham | last post by:
What's the canonical way to copy an array in C++? If we're copying a POD, we can use memcpy (but there could be a more efficient alternative if we know that the blocks are suitably aligned). Regardless of whether the array consists of POD's, we could use a loop such as: #include <cassert>
0
2733
by: ecestd | last post by:
I did implement the copy constructor but still have a problem with it. It is not working. What could be wrong? #include "QueueP.h" #include <cassert // for assert #include <new // for bad_alloc #include <iostream> //typedef std::queue<QueueItemTypeQueue; using namespace std; //private:{Queue::Queue(const Queue& Q)}
7
6412
by: Peter Olcott | last post by:
Why can a union have a member with a copy constructor?
0
8015
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
1
8094
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
8305
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
6770
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
5966
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
5465
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
3930
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...
1
2448
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
1
1553
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.