473,394 Members | 1,714 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.

Pushing memory allocating objects into a vector.

Hi.
I have some problems with a class i've written that allocates memory
dynamicaly. I want to put these objects into a std::vector, but it does
not work. My class looks (simplified) like this:

class Mem{
int *p, num;
public:
Mem(int a):p(0),n(a){
cout<< "created "<<num<<endl;
}
~Mem(){
if (p) delete []p;
cout << "destroyed "<<num<<endl;
}
void alloc(int i){
if (!p) p=new int[i];
}
};

My first attempt of creating a vector<Mem> was according to:

using namespace std;
int main(int argc, char* argv[])
{
vector<Mem> mv;
for (int i=0; i<3; i++){
cout << i<<endl;
Mem tmp(i);
tmp.alloc(10);
cout << "pushed"<<endl;
mv.push_back(tmp);
};
return 0;
}

However, this will not work as I create a temporary object tmp and lets
it allocate memory, then makes a bitwise copy of it that is pushed into
the vector. After this, tmp goes out of scope and deletes the memory it
had allocating, leaving the object in vector pointing to nonexisting
memory. Not good. (also, (not surprisingly) the program crashes, not
good at all)

So, how should i do this? My only present idea is to do something like:

vector<*Mem> ptrV;
for (int i=0; i<3; i++){
Mem *p=0;
ptrV.push_back(p);
ptrV[i] = new Mem(i);
ptrV[i].alloc(10);
}
(written on the fly, so it might contain some errors, just to show the
idea...)
But this leaves the problem of memoryleaks if im not careful to delete
all allocated memory manually before clearing or overwriting the vector.
I know there is a better way of doing this, but have no idea of what it is.

Also, i'd appreciate if someone could explain the output of the main()
function above. The output to console is:
0
created 0
pushed
destroyed 0
1
created 1
pushed
destroyed 0
destroyed 1
2
created 2
pushed
destroyed 0
destroyed 1
destroyed 2
<Then, the program crashes>

On e.g. iteration 2, why is object 0, 1, and 2 destroyed? An explanation
would hopefully help me understand this copy-creation a little better.

cheers
hall
--
( - Remove capital X from email to reply - )

Jul 19 '05 #1
4 2486
hall wrote:
Hi.
I have some problems with a class i've written that allocates memory
dynamicaly. I want to put these objects into a std::vector, but it
does not work. My class looks (simplified) like this:

class Mem{
int *p, num;
public:
Mem(int a):p(0),n(a){
cout<< "created "<<num<<endl;
}
~Mem(){
if (p) delete []p;
cout << "destroyed "<<num<<endl;
}
void alloc(int i){
if (!p) p=new int[i];
}
};


You need to implement a proper copy constructor and copy assigment operator.
Look up the rule of three.

WW aka Attila
Jul 19 '05 #2
> So, how should i do this?

If your class allocates memory to a pointer within it, you need to write a
copy constructor and assignment operator.
vector requires that the containee is copy constructible and assignable.
Currently your class is not.

Stephen Howe
Jul 19 '05 #3
White Wolf wrote:
hall wrote: [SNIP] You need to implement a proper copy constructor and copy assigment
operator. Look up the rule of three.


http://c2.com/cgi/wiki?RuleOfThree

http://www.comp.lancs.ac.uk/computin...slides/tsld067.
htm

Two descriptions of the rule of three. Basically what happens is that if
you have a pointer inside your class (pointing to something allocated by
your class) you need to manage that "hanging leaf" yourself:

On - An object of your class

An - The allocated thing

x - Nothing (NULL)

Mem O1;

O1 -> x

O1.alloc();

O1 -> A1

{Mem O2;

O1 -> A1
O2 -> x

O2.alloc();

O1 -> A1
O2 -> A2

O2 = O1 (something similar
happens inside the
vector during push_back)
O1 --> A1
O2 ----^
A2 (leaked memory)

} (scope closed, O2 is destructed)

O1 --> A1 (DELETED MEMORY!)

} (scope closed, O1 is destructed
and it tries to delete deleted
memory.)

BANG (if you are lucky.)

===

With the copy constructor the things will look a little bit different, but
not much. I hope this little "drawing" I made is understandable.

--
Attila aka WW
Jul 19 '05 #4
Attila Feher wrote:
White Wolf wrote:
hall wrote:
[SNIP]
You need to implement a proper copy constructor and copy assigment
operator. Look up the rule of three.

http://c2.com/cgi/wiki?RuleOfThree

http://www.comp.lancs.ac.uk/computin...slides/tsld067.
htm


And why don't I know of this rule? I should, but I don't. Found rule of
two in Stroustups book, but that was something quite different. Ah well,
now i know it :).

With the copy constructor the things will look a little bit different, but
not much. I hope this little "drawing" I made is understandable.

--
Attila aka WW


Yes, it does. Thanks!

/hall

--
<- remove capital x:s from e-mail to reply ->

Jul 19 '05 #5

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

Similar topics

6
by: J Anderson | last post by:
Greetings, I was going through the quake2 source code (as you do) when I noticed arrays are statically allocated on the stack instead of being allocated dynamically. I’ve seen this before and...
9
by: Alex Vinokur | last post by:
--------- #include <vector> using namespace std; struct Foo { Foo (int) {} }; int main () { vector<Foo> v1;
2
by: mosfets | last post by:
Hi, I'm having a little trouble figuring out the difference in terms of memory allocation between: class person_info; class A { private:
7
by: toton | last post by:
Hi, I have a STL vector of of characters and the character class has a Boost array of points. The things are vector<Characterchars; and class Character{ private: array<Point,Npoints; }; Now...
4
by: Dmytro Bablinyuk | last post by:
I came across several possible ways of allocating memory for objects, for example: 1. malloc(sizeof(T)*3)/free - raw memory 2. new T/delete - buffer would be initialized to...
81
by: Peter Olcott | last post by:
It looks like System::Collections::Generic.List throws and OUT_OF_MEMORY exception whenever memory allocated exceeds 256 MB. I have 1024 MB on my system so I am not even out of physical RAM, much...
20
by: Neclepsio | last post by:
Hi everyone. I've made a class Matrix, which contains a pointer to the data and some methods which all return a copy of the matrix modified in some way. The program works quite well for small...
5
by: cham | last post by:
Hi, I am working on c++ in a linux system ( Fedora core 4 ), kernel version - 2.6.11-1.1369_FC4 gcc version - 4.0.0 20050519 ( Red Hat 4.0.0-8 ) In my code i am creating a vector to store...
8
by: jacek.dziedzic | last post by:
Hi! I need to be able to track memory usage in a medium-sized application I'm developing. The only significant (memory-wise) non- local objects are of two types -- std::vector<and of a custom...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
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...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
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
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...
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.