Pointer-to-member-function code okay?

R

Ryan Mitchley

I am compiling under Visual C++ 2005 Express (with the Platform SDK
installed).

I have a class that is responsible for creating and repeatedly running
a Timeslice() method using a thread:

class cProcessBlock : public cBase
{
public:
. . .
virtual void Timeslice(); // executed repeatedly by a 'while' loop
in a thread
};

I also declare a function pointer typedef to handle cProcessBlock callbacks:

typedef void (cProcessBlock::*PortCallbackFnPtr)(shared_ptr<cBase>);

cProcessBlock has a descendant, cPort that registers callback methods
(in an STL map) and is responsible for calling these when objects are
received:

class cPort : public cProcessBlock
{
public:
. . .
void cPort::Timeslice()
// Continuously receive new objects and process using registered
callbacks
{
shared_ptr<cBase> pNewObject;
pNewObject = Receive();

// Call appropriate callback,
// depending on the received object's class name
if (pNewObject) {
PortCallbackFnPtr CallbackFn =
m_CallbackRegistry[pNewObject->ClassName()];
if (CallbackFn) // if callback handler is found
((*this).*(CallbackFn))(pNewObject);
}
}
map<string, PortCallbackFnPtr> m_CallbackRegistry;
}

I then define a descendant of cProcessBlock and create an instance:

class cBlockRx : public cProcessBlock {
public:
cBlockRx(. . .) {
m_pPort = shared_ptr<cPort>(new cPort);
m_pPort->AddCallback(static_cast<PortCallbackFnPtr>
(&cBlockRx::RxCallback), "cSomeObject");
m_streamOutput.open("Test.txt", ios::eek:ut);
};
void RxCallback(shared_ptr<cBase> pRx) {
m_streamOutput << "Got something" << endl << flush;
};

shared_ptr<cPort> m_pPort;
ofstream m_streamOutput;
} BlockRx;

When I start up the code that causes BlockRx to receive cSomeObjects,
the callback is entered correctly, although the output to the file
stream (m_streamOutput) bombs with an unhandled exception (access
violation) deep in the MS ostream code (the line begins "streamsize _Pad").

It bombs when I try a couple of other options in the callback too, which
leads me to suspect that I'm doing something nasty to the stack.

I guess I'm asking if the function pointer code above looks good, or if
there are reasons why I might be inviting "undefined behaviour".

I have also tried:
((*this).*static_cast<void(cProcessBlock::*)(shared_ptr<cBase>)>(CallbackFn))(pNewObject);
and ((*(static_cast<cProcessBlock*>(this))).*(CallbackFn))(pNewObject);
at the point where the callback is called. These were no better.

Thanks for any help!

Ryan
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,576
Members
45,054
Latest member
LucyCarper

Latest Threads

Top