473,320 Members | 1,863 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,320 software developers and data experts.

MemoryPool Class from Efficient C++ Failing

I'm currently fighting my way through an example of Single-Threaded
Memory Pooling in a chapter of the Efficient C++ book by Dov Bulka &
David Mayhew. Unfortuantely, I'm starting to get code that won't
compile and I am having a hard time finding an online errata or
contacting the authors.

For those familiar with the book, Chapter 6 covers rolling your own
memory manager. The first section, dealing with a Specialized Rational
Memory Manager (Rational is a custom class to handle fractions)
compiles fine, however the next sections fail. The first of these
sections is the Fixed-Size Object Memory Pool. The code, line for
line, reads at the end of this post.

My compile errors are with the lines referring to static_cast, saying
"Cannot convert from 'char *' to 'class MemoryPool<class Rational>*'.

I'd love to be able to figure this out, but sadly, that's why I'm
reading the book; I am not sure how this is failing. Any help would be
appreciated.

- Hanzo

=========

template<class T>
class MemoryPool
{
public:
MemoryPool(size_t size = EXPANSION_SIZE) {
expandTheFreeList(size); }
~MemoryPool();

// Allocate a T element from the free list
inline void *alloc(size_t size);

// Return a T element to the firee list
inline void free(void *someElement);
private:
// next element on the free list.
MemoryPool<T> *next;

// if the freeList is empty, expand it by this amount
enum { EXPANSION_SIZE = 32 };

// add free elements to the free list
void expandTheFreeList(int howMany = EXPANSION_SIZE);
};

template<class T>
MemoryPool<T>::~MemoryPool()
{
MemoryPool<T> *nextPtr = next;
for (nextPtr = next; nextPtr != NULL; nextPtr = next)
{
next = next->next;
delete [] nextPtr;
}
}

template<class T>
inline void* MemoryPool<T>::alloc(size_t size)
{
if (!next)
expandTheFreeList();

MemoryPool<T> *head = next;
next = head->next;

return head;
}

template<class T>
inline void MemoryPool<T>::free(void *doomed)
{
MemoryPool<T> *head = static_cast<MemoryPool<T>*>(doomed);

head->next = next;
next = head;
}

template<class T>
void MemoryPool<T>::expandTheFreeList(int howMany)
{
// We must allocate an object large enough to contain the
// next pointer
size_t size = (sizeof(T) > sizeof(MemoryPool<T>*)) ? sizeof(T)
: sizeof(MemoryPool<T>*);

MemoryPool<T> *runner = static_cast<MemoryPool<T>*>(new
char[size]);

next = runner;

for (int i=0; i<howMany; i++)
{
runner->next = static_cast<MemoryPool<T>*>(new
char[size]);
runner = runner->next;
}

runner->next = NULL;
}

// ===========================

class Rational {
public:
Rational(int a=0, int b=1) : n(a), d(b) {}

void *operator new(size_t size) { return memPool->alloc(size);
}
void operator delete(void *doomed, size_t size) {
memPool->free(doomed); }

static void newMemPool() { memPool = new MemoryPool<Rational>;
}
static void deleteMemPool() { delete memPool; }

private:
int n;
int d;

static MemoryPool<Rational> *memPool;
};

MemoryPool<Rational> *Rational::memPool = NULL;

int main()
{
Rational *array[1000];

Rational::newMemPool();

int start = timeGetTime();

for (int j=0; j<1; j++)
{
for (int i=0; i<1; i++)
{
array[i] = new Rational(i);
}
for (i=0; i<1; i++)
{
delete array[i];
}
}

int end = timeGetTime();

Rational::deleteMemPool();

cout << "The time was " << end-start << endl;

return 0;
}

Jul 19 '05 #1
4 3065
"Hanzo" <ha***@milclan.com> wrote in message
news:sk********************************@4ax.com...
[...]
My compile errors are with the lines referring to static_cast,
saying "Cannot convert from 'char *' to 'class
MemoryPool<class Rational>*'.
[...]
Usually, it's most polite to indicate the lines with the errors
in the posted code. That way, readers don't have to scan
through what may be hundreds of lines of unrelated code
just looking for the erroneous line.
[...]
MemoryPool<T> *runner = static_cast<MemoryPool<T>*>(new
char[size]);


I assume this is one of the lines that is giving you problems?
The problem is that there is no valid conversion from char*
to MemoryPool<T>*, just like the error says. So you need to
use an intermediate conversion to void*, like so:

MemoryPool<T> *runner =
static_cast<MemoryPool<T>*>(
static_cast<void*>(new char[size])
);

See if that works, and don't forget to fix the other occurence.

Dave

---
Outgoing mail is certified Virus Free.
Checked by AVG anti-virus system (http://www.grisoft.com).
Version: 6.0.521 / Virus Database: 319 - Release Date: 9/23/2003
Jul 19 '05 #2
On Sun, 19 Oct 2003 23:24:13 -0500, "David B. Held"
<dh***@codelogicconsulting.com> wrote:
Usually, it's most polite to indicate the lines with the errors
in the posted code. That way, readers don't have to scan
through what may be hundreds of lines of unrelated code
just looking for the erroneous line.
Sorry, I can never get that right. Sometimes I post a fragment and
then everyone wants to see more code. :)
MemoryPool<T> *runner =
static_cast<MemoryPool<T>*>(
static_cast<void*>(new char[size])
);

See if that works, and don't forget to fix the other occurence.


That definitely did work, thanks. However, there is still a problem in
execution, which I believe is tied to the line:

delete [] nextPtr;

in the destructor of MemoryPool<T>. Although that is line for line
what it has in the book (which have already proven wrong), is it
possible that the form of delete, as it seems fine with the array []
designation, should it be cast into some other type before the delete?

I dunno. I am just guessing here.

- Hanzo
Jul 19 '05 #3
"Hanzo" <ha***@milclan.com> wrote in message
news:5q********************************@4ax.com...
[...]
That definitely did work, thanks. However, there is still a problem
in execution, which I believe is tied to the line:

delete [] nextPtr;
Unlikely, since you are allocating your blocks with new char[...].
[...]
I dunno. I am just guessing here.


State what the actual erroneous output is, along with what you
think it should be, so I don't have to compile the code myself.
Help me help you. ;)

Dave

---
Outgoing mail is certified Virus Free.
Checked by AVG anti-virus system (http://www.grisoft.com).
Version: 6.0.521 / Virus Database: 319 - Release Date: 9/23/2003
Jul 19 '05 #4
On Mon, 20 Oct 2003 04:09:08 -0500, "David B. Held"
<dh***@codelogicconsulting.com> wrote:
State what the actual erroneous output is, along with what you
think it should be, so I don't have to compile the code myself.
Help me help you. ;)


On the line:

delete [] nextPtr;

I set a breakpoint. I execute to that line, and if I make one more
step, I get a general protection fault.

User breakpoint called from code at 0x77f75a58.

If I change it to this:

void* ptr = static_cast<void*>(nextPtr);
delete [] ptr;

The code executes without error. Now, whether or not i have a memory
leak is a different story.

- Hanzo

Jul 19 '05 #5

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

Similar topics

66
by: Mike Stenzler | last post by:
I am new to Template programming and I would like to create an array of user-defined class objects using MFC CArray. Normally I would use linked list processing - create an object class and then an...
3
by: Wang Tong | last post by:
Suppose I have a function foo() and a class definition myClass, and I want to create an instance of myClass and return it from foo(). I guess the most efficient way is to return a reference to the...
15
by: Steven T. Hatton | last post by:
The following may strike many of you as just plain silly, but it represents the kind of delelima I find myself in when trying to make a design decision. This really is a toy project written for...
8
by: SpOiLeR | last post by:
Hello! I have a matrix class like this: class MyObject; // MyMatrix is contains MyObjects class MyMatrix { public: ...
12
by: keepyourstupidspam | last post by:
Hi, I am writing a windows service. The code runs fine when I start the service when my machine is running but it fails to start automatically when the machine reboots. The code bombs out when...
12
by: mast2as | last post by:
Hi everyone I am working on some code that uses colors. Until recently this code used colors represented a tree floats (RGB format) but recently changed so colors are now defined as spectrum....
6
by: JoeC | last post by:
I have a question about designing objects and programming. What is the best way to design objects? Create objects debug them and later if you need some new features just use inhereitance. Often...
3
by: antred | last post by:
Hello everyone, While working on a program I encountered a situation where I'd construct a largish data structure (a tree) from parsing a host of files and would end up having to throw away...
4
by: AndrewD | last post by:
Hey C++ folks, I created this today, just for fun. You can make object allocation for any class around 6 times faster, simply by doing the following. class MyClass : public...
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
0
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....

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.