473,394 Members | 1,841 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,394 software developers and data experts.

Iterator and handle confusion

I was having some issues with a program involving iterators and handles,
and decided to try and make a short test program to try to work out where
my problem was. However, my test program went wrong long before it
resembled anything like my actual program.

Here is the short test program:

#include <iostream>
#include <list>

using std::cout;
using std::endl;
using std::list;

int globalCounter = 0;

class MyClass
{
public:
MyClass() {classCounter = globalCounter++;}

int classCounter;
};

class MyHandle
{
public:
MyHandle() {myPointer = new MyClass; handleCounter = myPointer->classCounter;}
~MyHandle() {delete myPointer;}
int GetCounter() {return myPointer->classCounter;}

int handleCounter;

private:
MyClass* myPointer;
};

int main()
{
list<MyHandle> myList;

for (int i = 0; i != 10; ++i)
myList.push_back(MyHandle());

for (list<MyHandle>::iterator iter = myList.begin(); iter != myList.end(); ++iter)
cout << iter->handleCounter << " " << iter->GetCounter() << endl;

return 0;
}

The output I get is:

0 0
1 0
2 0
3 0
4 0
5 0
6 0
7 0
8 0
9 0

But I was expecting:

0 0
1 1
2 2
3 3
4 4
5 5
6 6
7 7
8 8
9 9

Where have I gone wrong?

Thanks,

James
Jul 22 '05 #1
4 1350
"James Gregory" <ja****@f2s.com> wrote in message
news:pa****************************@f2s.com...
I was having some issues with a program involving iterators and handles,
and decided to try and make a short test program to try to work out where
my problem was. However, my test program went wrong long before it
resembled anything like my actual program.

Here is the short test program:

#include <iostream>
#include <list>

using std::cout;
using std::endl;
using std::list;

int globalCounter = 0;

class MyClass
{
public:
MyClass() {classCounter = globalCounter++;}

int classCounter;
};

class MyHandle
{
public:
MyHandle() {myPointer = new MyClass; handleCounter = myPointer->classCounter;} ~MyHandle() {delete myPointer;}
The rule of 3: if a class has a destructor, a copy constructor, or an
assignment operator, it probably needs all three. Your code actually crashes
on my compiler because you disobeyed this rule. Add the following:

MyHandle(const MyHandle &other) {myPointer = new MyClass; handleCounter =
other.handleCounter;}
MyHandle &operator = (const MyHandle &other)
{
if (&other != this)
{
delete myPointer;
myPointer = new MyClass;
handleCounter = other.handleCounter;
}
return *this;
}
int GetCounter() {return myPointer->classCounter;}

int handleCounter;

private:
MyClass* myPointer;
};

int main()
{
list<MyHandle> myList;

for (int i = 0; i != 10; ++i)
myList.push_back(MyHandle());

for (list<MyHandle>::iterator iter = myList.begin(); iter != myList.end(); ++iter) cout << iter->handleCounter << " " << iter->GetCounter() << endl;

return 0;
}

The output I get is:

0 0
1 0
2 0
3 0
4 0
5 0
6 0
7 0
8 0
9 0

But I was expecting:

0 0
1 1
2 2
3 3
4 4
5 5
6 6
7 7
8 8
9 9

Where have I gone wrong?

Thanks,

James


The corrected output is:

0 1
2 3
4 5
6 7
8 9
10 11
12 13
14 15
16 17
18 19

which I believe is correct when you account for the fact that a copy is made
during the push_back.

--
Cy
http://home.rochester.rr.com/cyhome/
Jul 22 '05 #2

"James Gregory" <ja****@f2s.com> wrote in message
news:pa****************************@f2s.com...
I was having some issues with a program involving iterators and handles,
and decided to try and make a short test program to try to work out where
my problem was. However, my test program went wrong long before it
resembled anything like my actual program.
Good strategy.

Here is the short test program:

#include <iostream>
#include <list>

using std::cout;
using std::endl;
using std::list;

int globalCounter = 0;

class MyClass
{
public:
MyClass() {classCounter = globalCounter++;}

int classCounter;
};

class MyHandle
{
public:
MyHandle() {myPointer = new MyClass; handleCounter = myPointer->classCounter;} ~MyHandle() {delete myPointer;}
int GetCounter() {return myPointer->classCounter;}

int handleCounter;

private:
MyClass* myPointer;
};

int main()
{
list<MyHandle> myList;

for (int i = 0; i != 10; ++i)
myList.push_back(MyHandle());

for (list<MyHandle>::iterator iter = myList.begin(); iter != myList.end(); ++iter) cout << iter->handleCounter << " " << iter->GetCounter() << endl;

return 0;
}

The output I get is:

0 0
1 0
2 0
3 0
4 0
5 0
6 0
7 0
8 0
9 0

But I was expecting:

0 0
1 1
2 2
3 3
4 4
5 5
6 6
7 7
8 8
9 9

Where have I gone wrong?

Thanks,

James


What you've done wrong is to ignore the issue of copying. EVERY TIME you
create a class, you should ask yourself the question 'what happens if an
object of this class is copied?'. If you look at your MyHandle class, then
if a MyHandle object is copied it will get a copy of the myPointer member
variable. Now what happens if the original MyHandle object is deleted? Your
copy will still be holding a pointer to a now deleted MyClass object. I
think you were lucky to get the program to run at all, it crashed when I ran
it with my compiler.

What is actually happening is this program is that you create a MyHandle
object, then the std::list takes a copy of the object, the original is
destroyed, deleting the myPointer pointer in its destructor, so you have an
object on a list that contains a pointer to a now deleted object. Hence (in
your case) the zeros.

Try this

class MyHandle
{
// code as before

/* copy constructor, called when the object is copied */
MyHandle(const MyHandle& x)
{
myPointer = new MyClass;
handleCounter = myPointer->classCounter;
}

/* assignment operator, called when the object is assigned (doesn't
actually happen in your program) */
MyHandle& operator=(const MyHandle& x)
{
return *this;
}

};

Of course the copy semantics I have chosen might not be the ones you want,
but at least I defined some sort of sensible copying behaviour whereas
you've just ignored the issue.

Any decent C++ book will cover this issue, you might also want to look up
the topic of reference counting.

John
Jul 22 '05 #3
On Sat, 07 Feb 2004 20:13:13 +0000, James Gregory wrote:

<snip>

Many thanks for the replies, I forgot about how important dealing with
copying is.

However, my "real" program does actually have a copy constructor and
reference counting in the handle, which I added after "reading a good C++
book", so I've still got to work a bit more to find my main problem.

James

Jul 22 '05 #4
Hello, James!
You wrote on Sat, 07 Feb 2004 20:13:13 +0000:

JG> I was having some issues with a program involving iterators and

[Sorry, skipped]

JG> class MyHandle
JG> {
JG> public:
JG> MyHandle() {myPointer = new MyClass; handleCounter =
JG> myPointer->classCounter;} ~MyHandle() {delete myPointer;}
JG> int GetCounter() {return myPointer->classCounter;}

[Sorry, skipped]

JG> for (int i = 0; i != 10; ++i)
JG> myList.push_back(MyHandle());

Here it creates an instance of MyHandle
Then copies its contents into the list using bitwise copy (no user defined
operator= was provided)
Then destructor of MyHandle is called, invalidating the pointer

Booom, you've got a whole list of garbage :)

Vyacheslav Lanovets
Jul 22 '05 #5

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

Similar topics

38
by: Grant Edwards | last post by:
In an interview at http://acmqueue.com/modules.php?name=Content&pa=showpage&pid=273 Alan Kay said something I really liked, and I think it applies equally well to Python as well as the languages...
5
by: music4 | last post by:
Greetings, I want to STL map class. But I don't know how to use iterator. Let me state my question by following small sample: map<int, int> mymap; // insert some <key,value> in mymap ...
1
by: Steve H | last post by:
From "C++ Programming Language (3rd Edition)" I understand that there are 5 standard iterator categories defined in the "std" namespace: Output *p= p++ Input =*p -> ++ == !=...
2
by: wenmang | last post by:
Hi, all: I am reading the book "The C++ Stadnard Library" by Josuttis. I have trouble to understand operations for the insert iterator(page 272). ++itr, *itr and itr++ are defined as no-op, and...
14
by: shawnk | last post by:
I searched the net to see if other developers have been looking for a writable iterator in C#. I found much discussion and thus this post. Currently (C# 2) you can not pass ref and out arguments...
0
by: mailforpr | last post by:
Hi. Let me introduce an iterator to you, the so-called "Abstract Iterator" I developed the other day. I actually have no idea if there's another "Abstract Iterator" out there, as I have never...
21
by: T.A. | last post by:
I understand why it is not safe to inherit from STL containers, but I have found (in SGI STL documentation) that for example bidirectional_iterator class can be used to create your own iterator...
7
by: Jess | last post by:
Hello, I learned that if we do "v.end()", then the returned iterator is a temporary object and hence cannot be changed like --v.end(); Why is the returned iterator a temporary pointer? I...
3
by: Rune Allnor | last post by:
Hi folks. I have a function that takes an element in a vector as argument. The naive interface goes as float computeSomething(const std::vector<float>& v, size_t i) { size_t j = i-1; size_t...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
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...
0
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,...
0
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...
0
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...

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.