std::vector and function pointers

Started by
3 comments, last by Telastyn 18 years, 3 months ago
In an attempt at trying my hand at making a GUI, I came across a use for function poitners (linking a function to a GUI item, like a button). However, I ran into problems when I tried to make a vector of objects that contained function pointers. When I called the .push_back() to put the object containing the function pointers into the vector, the memory at the point of the function pointer and beyond becomes unreliable. A second call to .push_back() results in unpredicable behavior (ranging from a run-time error to the program eating up megs of RAM). Removing the function pointer member variable from the object stops all strange behavior. In the mean time, I've resorted to using a simple array of function pointers and storing an index ID with the object so it can look up the function it needs. Does anyone have any ideas why vectors/push_back would not play nice with function pointers? I'm using MSVC 2005 Express.
Advertisement
I don't know offhand, but using boost::function is a quick, easy, and flexible workaround.
There should be absolutely nothing wrong with storing pointers to functions in std::vector, show us a short example of exactly how you used it and take note that pointer to member function != pointer to function.
Quote:Original post by Telastyn
I don't know offhand, but using boost::function is a quick, easy, and flexible workaround.


I doubt using boost::function is going to magically solve what sounds like one of the following:

1) Behavior invoked from misuse of the function pointer array (use of uninitialized function pointers?)
2) Behavior invoked from memory fun fun happy time (memory overflows, dangling pointers, etc)
3) ???
Perhaps not, but their use [imo] makes finding #1 easier, and [really imo] makes the majority of #3 (mistakes caused by the awkward syntax of C++ function pointers) harder to make.

This topic is closed to new replies.

Advertisement