I have some problems with understanding function pointers. Although I've read lots of topics on this I still have problems with the follow case.
My example is simple - I have a joystick class which has some function pointers as well as functions through which these pointers can be assigned and I don't know how to do this properly.
I'll try to keep it simple:
class Joystick {
void (Player::*OnShootKeyPressed)(); // pointer that takes no arguments and returns nothing
void SetCallback(void (Player::*f)) {
OnShotKeyPressed = f;
}
}
class Player {
void OnShootAction() { ...do the shooting...}
void Initialize() {
Joystick* joy = pInputMng->GetJoystick();
joy->SetCallback( &Player::OnShootAction() );
}
}
--Edited after Captain Obvlious comment--
That's one short example of what I want to achieve and I don't seem to understand these function pointers correctly. What am I doing wrong?
I appreciate all the help in advance!
I love function pointers. I consider them among my best personal friends. But this is probably not the time for them. When you have whole objects calling each other back and forth, Just pass the object.
If you need greater decoupling between the objects, build an interface. I'll go with the interface route because why not? Once you've seen the hard way, the easy way's easy.
First, define an interface for users of the joystick
class ButtonUser
{
virtual void OnShootAction() = 0; // function to be implemented by children
virtual void OnJumpAction() = 0;
virtual void OnDeathBlossomAction() = 0;
...
}
Now a joystick that uses the button interface and knows absolutely nothing about Player
class Joystick {
ButtonUser * pUser;
void SetCallback(ButtonUser * puser) {
pUser = puser;
}
void OnKeyPressed(key) {
if (pUser != NULL) {
switch( key ) {
case SHOOT:
pUser->OnShootAction();
break;
case JUMP:
pUser->OnjumpAction();
break;
case DB:
pUser->OnDeathBlossomAction();
break;
...
}
}
}
}
And Player installs itself as Joystick's user
class Player: public ButtonUser{
void OnShootAction() { ...do the shooting...}
void OnJumpAction() {...jump...};
void OnDeathBlossomAction() {...blow $#!+ up!...}
...
void Initialize() {
Joystick* joy = pInputMng->GetJoystick();
joy->SetCallback( this );
}
CORRECTED CODE & ANSWER
1.) I was having some problems with namespaces not mentioned in the question so I wasn't able to create a function.
Both classes were under the namespace so the function for assigning a function pointer was rejected:
void SetCallback(void (ehJoystick::*f)())
It was required to be this instead:
void SetCallback(void (eg::ehJoystick::*f)())
But then, compiler didn't accept the namespace infront of that. I thought I was doing something wrong elsewhere but there problem was there all the time.
2.) I didn't know you need an object reference where you want to call a member function pointer. Following code is correct and working.
class Joystick {
Player* pPlayer;
void (Player::*OnShootKeyPressed)() = NULL; // pointer that takes no arguments and returns nothing
void SetCallback(void (Player::*f)(), Player *p) {
OnShotKeyPressed = f;
pPlayer = p; // we need a reference to the object
}
void OnKeyPressed(key) {
if( key == SHOOT && OnShootKeyPressed != NULL ) {
(pPlayer->*OnShootKeyPressed)(); //that's how the function is called
}
}
class Player {
void OnShootAction() { ...do the shooting...}
void Initialize() {
Joystick* joy = pInputMng->GetJoystick();
joy->SetCallback( &Player::OnShootAction, this );
}
Related
I am building a console application in wich I am only using smart pointers. I made the choice to only use smart pointers to learn when to use which smart pointer. In this application, I am trying to use a state pattern to switch between the different states. The base class is TurnState from this class all the other state-classes inherit.
In the gamecontroller, I have defined the current state. For switching between the states I want to use an unordered_map with an enum as key and the state class as value. But as soon as I wrote down std::unordered_map<TurnStateEnum, std::shared_ptr<TurnState>> _turn_states_map; inside the header I got some memory leaks.
To get rid of those memory leaks I tried to destroy them in the deconstructor like this:
GameController::~GameController()
{
for (std::unordered_map<TurnStateEnum, std::shared_ptr<TurnState>>::iterator iterator{ _turn_states_map.begin() }; iterator != _turn_states_map.end(); iterator++) {
iterator->second.reset();
_turn_states_map.erase(iterator);
}
_turn_states_map.clear();
}
But that did not work out either. I was able to solve it using raw pointers but that is not what I am trying to achieve. So my question is, how do I delete a map with shared_ptrs in the correct way?
All help will be appreciated.
Edit 1 - Minimal example
The Game Controller will be used for holding a shared_ptr to the current state and switching to the next one.
Below is the GameController header:
class GameController
{
public:
GameController();
~GameController();
void do_action(Socket& client, Player& player, std::string command);
void set_next_state(TurnStateEnum state);
private:
std::unordered_map<TurnStateEnum, std::shared_ptr<TurnState>> _turn_states_map;
std::shared_ptr<TurnState> _turn_state;
void initialize_turn_states_map();
};
Below is the GameController source:
GameController::GameController()
{
initialize_turn_states_map();
_turn_state = _turn_states_map.at(TurnStateEnum::SETUP);
}
GameController::~GameController()
{
for (std::unordered_map<TurnStateEnum, std::shared_ptr<TurnState>>::iterator iterator{ _turn_states_map.begin() }; iterator != _turn_states_map.end(); iterator++) {
iterator->second.reset();
_turn_states_map.erase(iterator);
}
_turn_states_map.clear();
}
void GameController::do_action(Socket& client, Player& player, std::string command)
{
_turn_state->do_turn(client, player, command);
}
void GameController::set_next_state(TurnStateEnum state)
{
_turn_state = _turn_states_map.at(state);
}
void GameController::initialize_turn_states_map()
{
_turn_states_map.insert(std::make_pair(TurnStateEnum::SETUP, std::make_shared<SetupState>(*this)));
}
The TurnState is the base class. This class should contain the current logic/behaviour of the application.
Below the TurnState header:
class GameController;
class TurnState
{
public:
TurnState(GameController& gameCtrl);
virtual ~TurnState();
void next_state(TurnStateEnum stateEnum);
virtual void do_turn(Socket& client, Player& player, std::string command) = 0;
protected:
GameController& _gameCtrl;
};
Below the TurnState source:
TurnState::TurnState(GameController& gameCtrl) : _gameCtrl ( gameCtrl )
{
}
TurnState::~TurnState()
{
}
void TurnState::next_state(TurnStateEnum stateEnum)
{
_gameCtrl.set_next_state(stateEnum);
}
Setup State does not have any other variables or methods than his base class and for now, the methods are empty.
Edit 2 - Minimal example v2
This might be a better minimal example. I created a console project and uploaded it to: https://ufile.io/ce79d
There are no leaks in your program. You are using std::shared_ptr correctly. There are no circular references to fix. Although the destructors were redundant, they were harmless.
You are just not using _CrtDumpMemoryLeaks() right. You are calling it before destructors for local objects in main are run. Naturally it will report memory allocated by these objects as leaks.
To fix:
int main(int argc, const char * argv[])
{
(
GameController gameCtrl = GameController();
gameCtrl.do_action("test");
}
_CrtDumpMemoryLeaks();
return 0;
}
So I've been cleaning up a bit of code, and I noticed that the desctructor of a class was being called directly after the constructer is called. Effectively, the object does nothing. Im pretty sure the object is still in scope, because I can access its members still. In the constructer I've printed out this and in the destructor I've printed out "deleted: " << this. Here is what the output looks like:
x7fff5fbff380
0x7fff5fbff3d0
deleted: 0x7fff5fbff3d0
deleted: 0x7fff5fbff380
0x7fff5fbff280
0x7fff5fbff2d0
deleted: 0x7fff5fbff2d0
deleted: 0x7fff5fbff280
0x7fff5fbff190
0x7fff5fbff1e0
deleted: 0x7fff5fbff1e0
deleted: 0x7fff5fbff190
Obviously, this isn't enough to help solve the problem, so here is some code, involving how the object is created, how it is used and how it is destroyed.
//event listener constructor
EventListener::EventListener(EventTypes typeEvent,EventFunction functionPointer)
{
this->typeEvent = typeEvent;
this->functionPointer = functionPointer;
//add it to the tick handler
this->listenerID = EngineEventDispacher.addEventListener(this);
std::cout << this << std::endl;
}
void EventListener::removeListener()
{
//remove it from the tickHandler
EngineEventDispacher.removeEventListener(this->listenerID);
}
//we add the event listener here
int EventDispatcher::addEventListener(EventListener* listener)
{
EventListeners.push_back(listener);
return (int)EventListeners.size() - 1;
}
//get rid of a listener
void EventDispatcher::removeEventListener(int id)
{
//std::vector<EventListener*>::iterator it;
//it = EventListeners.begin() + id;
//EventListeners.erase(it);
// EventListeners.shrink_to_fit();
//this isnt very memory efficiant, but it is the best solution for the CPU
EventListeners[id] = nullptr;
}
//send an event to all the listeners that can have it
void EventDispatcher::dispatchEvent(EventTypes eventType, Event* event)
{
for (int i = 0; i < EventListeners.size(); i++)
{
//we check if the current listener is subscribed to the event we are calling
if (EventListeners[i] != nullptr)
if (EventListeners[i]->typeEvent == eventType && EventListeners[i]->functionPointer != 0 )
{
//it was subscribed, so we are going to call it
EventListeners[i]->functionPointer(event);
}
}
}
//make sure that we can't call this
EventListener::~EventListener()
{
EngineEventDispacher.removeEventListener(this->listenerID);
std::cout << "deleted: " << this << std::endl;
}
What the classes look like:
//This will recive events
class EventListener
{
//this is what type of event it will repsond to
public:
EventTypes typeEvent;
EventListener(EventTypes typeEvent, EventFunction);
EventListener();
~EventListener();
EventFunction functionPointer;
void removeListener();
private:
int listenerID;
};
//her we define the event dispatcher
class EventDispatcher
{
public:
int addEventListener(EventListener*);
void removeEventListener(int);
void dispatchEvent(EventTypes, Event*);
private:
std::vector<EventListener*>EventListeners;
};
And finally how the event listener is declared and constructed:
class Scene
{
public:
Scene();
std::vector<StaticGeometry>GameObjects;
void addStaticGeometry(StaticGeometry object);
void renderSceneWithCamera(camera cam);
void renderSceneWithCameraAndProgram(camera cam,GLuint program);
void pickObjectFromScene();
void pickObjectFromSceneWithScreenCoords(int x, int y);
int selectedObject;
private:
//listen for the left click
EventListener leftClickEventListener;
void leftClick(Event* eventPtr);
};
Scene::Scene() : leftClickEventListener(EventTypeLeftMouseClick,std::bind(&Scene::leftClick,this,std::placeholders::_1))
{
//default constructor, we just need to make sure that the selected thing is -1
selectedObject = -1;
}
As far as I know, members aren't supposed to call the deconstructor until the parent calls theirs. The Scene class most definitely isn't calling its reconstructor, and thats what really has me puzzled. Everything should be fine, but its not. Nothing I've found says that things should just randomly decide to deconstruct themselves. Any help would be appreciated. Thanks.
Problem:
If you create an object inside a block or function with automatic storage duration, like
{
// ...
EventListener myListener();
// ...
}
the object will be destroyed as soon as execution leaves the block/function, even though it may still be referenced from elsewhere. See also:
Creating an object: with or without `new`
Generally, you should never pass a pointer to an object with such scope anywhere where it might be stored internally.
Solution:
You'll have to explicitly use new if you want your object to live beyond the current block:
{
// ...
EventListener* myListener = new EventListener();
// ...
}
Im pretty sure the object is still in scope, because I can access its
members still.
Beware: A pointer to an object may still seem to be usable even after the object has been (implicitly) destroyed, but dereferencing this pointer is a severe, though not always obvious, bug.
I have a class called woodyard. Inside there is a method called collect_wood. It's parameter is a Player object. The method adds 1 to player.wood_resource each time it is called.
I use it in main like this:
for(int i = 0; i < woodyards.size(); i++)
{
woodyards[i].collect_wood(p1);
}
p1 is a player object.
This is the collect_wood method:
void woodyard::collect_wood(Player player)
{
player.wood_resource++;
}
There is no effect on wood_resource when I run it.
Please help. I'm coding in C++ using CodeBlocks
You should use reference here.
void woodyard::collect_wood(Player& player)
{
player.wood_resource++;
}
since in your case - you increment wood_resource of copy.
Do it as Call By Reference. What your code does, it creates new Player each time instead of modifying old one.
void woodyard::collect_wood(Player& player)
{
player.wood_resource++;
}
Note & in void woodyard::collect_wood(Player& player)
You can read more about Function call by reference here
By default the functions are call by value (exceptions are there). If you need to change the original copy and not the temporary object you need to use references or pointers.
You any of the two functions:
void woodyard::collect_wood(Player& player)
{
player.wood_resource++;
}
OR
void woodyard::collect_wood(Player *player)
{
if(player)
{
*player.wood_resource++;
}
}
Is there a way, I can switch between 2 similar function sets (C/C++) in an effective way?
To explain better what I mean, lets say I have 2 sets of global functions like:
void a_someCoolFunction();
void a_anotherCoolFunction(int withParameters);
…
void b_someCoolFunction();
void b_anotherCoolFunction(int withParameters);
…
And I want to able to "switch" in my program at runtime which one is used. BUT: I dont want to have one if condition at every function, like:
void inline someCoolFunction(){
if(someState = A_STATE){
a_someCoolFunction();
}else{
b_someCoolFunction();
}
}
Because, I expect that every function is called a lot in my mainloop - so It would be preferable if I could do something like this (at start of my mainloop or when someState is changed):
if(someState = A_STATE){
useFunctionsOfType = a;
}else{
useFunctionsOfType = b;
}
and then simply call
useFunctionsOfType _someCoolFunction();
I hope its understandable what I mean… My Background: Im writing an App, that should be able to handle OpenGL ES 1.1 and OpenGL ES 2.0 both properly - but I dont want to write every render Method 2 times (like: renderOpenGL1() and renderOpenGL2() I would rather to write only render()). I already have similiar Methods like: glLoadIdentity(); myLoadIdentity(); … But need a way to switch between these two somehow.
Is there any way to accomplish this in an efficent way?
Several options, including (but not limited to):
Use function pointers.
Wrap them in classes, and use polymorphism.
Have two separate copies of the loop.
But please profile to ensure this is actually a problem, before you make any large changes to your code.
As the question seems to be interested in a C++ solution and no-one has spelt out the polymorphic solution (too obvious?), here goes.
Define an abstract base class with the API you require, and then implement a derived class for each supported implementation:
class OpenGLAbstract
{
public:
virtual ~OpenGLAbstract() {}
virtual void loadIdentity() = 0;
virtual void someFunction() = 0;
};
class OpenGLEs11 : public OpenGLAbstract
{
public:
virtual void loadIdentity()
{
// Call 1.1 API
}
virtual void someFunction()
{
// Call 1.1 API
}
};
class OpenGLEs20 : public OpenGLAbstract
{
public:
virtual void loadIdentity()
{
// Call 2.0 API
}
virtual void someFunction()
{
// Call 2.0 API
}
};
int main()
{
// Select the API to use:
bool want11 = true;
OpenGLAbstract* gl = 0;
if (want11)
gl = new OpenGLEs11;
else
gl = new OpenGLEs20;
// In the main loop.
gl->loadIdentity();
delete gl;
}
Note that this is exactly the sort of thing that C++ was intended for, so if can use C++ here, this is the simplest way to go.
Now a more subtle issue you might face is if your 2.0 version requires the process to load a dynamic linked library at run time with the 2.0 platform implementation. In that case just supporting the API switch is not enough (whatever the solution). Instead put each OpenGL concrete class in its own linked library and in each provide a factory function to create that class:
OpenGlAbstract* create();
Then load the desired library at run time and call the create() method to access the API.
In C (since it seems you want both C and C++) this is done with pointer to functions.
// Globals. Default to the a_ functions
void(*theCoolFunction)() = a_someCoolFunction;
void(*theOtherCoolFunction)(int) = a_anotherCoolFunction;
// In the code ...
{
...
// use the other functions
theCoolFunction = b_someCoolFunction;
theOtherCoolFunction = b_anotherCoolFunction;
...
}
You might probably want to switch those functions in groups, so you better set a array of pointers to functions and pass that array around. If you decide to do so, you might probably want to also define some macro to ease the reading:
void (*functions_a[2])();
void (*functions_b[2])();
void (**functions)() = functions_a;
....
#define theCoolFunction() functions[0]()
#define theOtherCoolFunction(x) functions[1](x)
....
// switch grooup:
functions = functions_b;
but in this case you'll lose the static check on argument types (and you have to initialize the array, of course).
I guess in C++ you will have instatiate two different objects with the same parent class and different implementation for their methods (but I'm no C++ prograammer!)
You could use functions pointers. You can read a lot about them if you google it, but briefly a function pointer stores a pointer to a function's memory address.
Function pointers can be used the same way as a funcion, but can be assigned the address of different functions, making it a somehow "dynamic" function. As an example:
typedef int (*func_t)(int);
int divide(int x) {
return x / 2;
}
int multiply(int x) {
return x * 2;
}
int main() {
func_t f = ÷
f(2); //returns 1
f = &multiply;
f(2); //returns 4
}
Something like boost::function (std::function) would fit the bill. Using your example:
#include <iostream>
#include <boost/function.hpp> //requires boost installation
#include <functional> //c++0x header
void a_coolFunction() {
std::cout << "Calling a_coolFunction()" << std::endl;
}
void a_coolFunction(int param) {
std::cout << "Calling a_coolFunction(" << param << ")" << std::endl;
}
void b_coolFunction() {
std::cout << "Calling b_coolFunction()" << std::endl;
}
void b_coolFunction(int param) {
std::cout << "Calling b_coolFunction(" << param << ")" << std::endl;
}
float mul_ints(int x, int y) {return ((float)x)*y;}
int main() {
std::function<void()> f1; //included in c++0x
boost::function<void(int)> f2; //boost, works with current c++
boost::function<float(int,int)> f3;
//casts are necessary to resolve overloaded functions
//otherwise you don't need them
f1 = static_cast<void(*)()>(a_coolFunction);
f2 = static_cast<void(*)(int)>(a_coolFunction);
f1();
f2(5);
//switching
f1 = static_cast<void(*)()>(b_coolFunction);
f2 = static_cast<void(*)(int)>(b_coolFunction);
f1();
f2(7);
//example from boost::function documentation. No cast required.
f3 = mul_ints;
std::cout << f3(5,3) << std::endl;
}
Compiled with g++-4.4.4, this outputs:
Calling a_coolFunction()
Calling a_coolFunction(5)
Calling b_coolFunction()
Calling b_coolFunction(7)
15
The biggest limitation is that the types of f1,f2, etc cannot change, so any function you assign to them must have the same signature (i.e. void(int) in the case of f2).
The simple way could be storing pointers to functions, and change them od demand.
But the better way is to use something similar to abstract factory design pattern. The nice generic implementation can be found in Loki library.
In C you would typically do this with a struct containing function pointers:
struct functiontable {
void (*someCoolFunction)(void);
void (*anotherCoolFunction)(int);
};
const struct functiontable table_a = { &a_someCoolFunction, &a_anotherCoolFunction };
const struct functiontable table_b = { &b_someCoolFunction, &b_anotherCoolFunction };
const struct functiontable *ftable = NULL;
To switch the active function table, you'd use:
ftable = &table_a;
To call the functions, you'd use:
ftable->someCoolFunction();
Here is my issue.
I have a class to create timed events. It takes in:
A function pointer of void (*func)(void* arg)
A void* to the argument
A delay
The issue is I may want to create on-the-fly variables that I dont want to be a static variable in the class, or a global variable. If either of these are not met, I cant do something like:
void doStuff(void *arg)
{
somebool = *(bool*)arg;
}
void makeIt()
{
bool a = true;
container->createTimedEvent(doStuff,(void*)&a,5);
}
That wont work because the bool gets destroyed when the function returns. So I'd have to allocate these on the heap. The issue then becomes, who allocates and who deletes. what I'd like to do is to be able to take in anything, then copy its memory and manage it in the timed event class. But I dont think I can do memcpy since I dont know the tyoe.
What would be a good way to acheive this where the time event is responsible for memory managment.
Thanks
I do not use boost
class AguiTimedEvent {
void (*onEvent)(void* arg);
void* argument;
AguiWidgetBase* caller;
double timeStamp;
public:
void call() const;
bool expired() const;
AguiWidgetBase* getCaller() const;
AguiTimedEvent();
AguiTimedEvent(void(*Timefunc)(void* arg),void* arg, double timeSec, AguiWidgetBase* caller);
};
void AguiWidgetContainer::handleTimedEvents()
{
for(std::vector<AguiTimedEvent>::iterator it = timedEvents.begin(); it != timedEvents.end();)
{
if(it->expired())
{
it->call();
it = timedEvents.erase(it);
}
else
it++;
}
}
void AguiWidgetBase::createTimedEvent( void (*func)(void* data),void* data,double timeInSec )
{
if(!getWidgetContainer())
return;
getWidgetContainer()->addTimedEvent(AguiTimedEvent(func,data,timeInSec,this));
}
void AguiWidgetContainer::addTimedEvent( const AguiTimedEvent &timedEvent )
{
timedEvents.push_back(timedEvent);
}
Why would you not use boost::shared_ptr?
It offers storage duration you require since an underlying object will be destructed only when all shared_ptrs pointing to it will have been destructed.
Also it offers full thread safety.
Using C++0x unique_ptr is perfect for the job. This is a future standard, but unique_ptr is already supported under G++ and Visual Studio. For C++98 (current standard), auto_ptr works like a harder to use version of unique_ptr... For C++ TR1 (implemented in Visual Studio and G++), you can use std::tr1::shared_ptr.
Basically, you need a smart pointer. Here's how unique_ptr would work:
unique_ptr<bool> makeIt(){ // More commonly, called a "source"
bool a = true;
container->createTimedEvent(doStuff,(void*)&a,5);
return new unique_ptr<bool>(a)
}
When you use the code later...
void someFunction(){
unique_ptr<bool> stuff = makeIt();
} // stuff is deleted here, because unique_ptr deletes
// things when they leave their scope
You can also use it as a function "sink"
void sink(unique_ptr<bool> ptr){
// Use the pointer somehow
}
void somewhereElse(){
unique_ptr<bool> stuff = makeIt();
sink(stuff);
// stuff is now deleted! Stuff points to null now
}
Aside from that, you can use unique_ptr like a normal pointer, aside from the strange movement rules. There are many smart pointers, unique_ptr is just one of them. shared_ptr is implemented in both Visual Studio and G++ and is the more typical ptr. I personally like to use unique_ptr as often as possible however.
If you can't use boost or tr1, then what I'd do is write my own function that behaves like auto_ptr. In fact that's what I've done on a project here that doesn't have any boost or tr1 access. When all of the events who care about the data are done with it it automatically gets deleted.
You can just change your function definition to take in an extra parameter that represents the size of the object passed in. Then just pass the size down. So your new function declarations looks like this:
void (*func)(void* arg, size_t size)
void doStuff(void *arg, size_t size)
{
somebool = *(bool*)arg;
memcpy( arg, myStorage, size );
}
void makeIt()
{
bool a = true;
container->createTimedEvent(doStuff,(void*)&a,sizeof(bool), 5);
}
Then you can pass variables that are still on the stack and memcpy them in the timed event class. The only problem is that you don't know the type any more... but that's what happens when you cast to void*
Hope that helps.
You should re-work your class to use inheritance, not a function pointer.
class AguiEvent {
virtual void Call() = 0;
virtual ~AguiEvent() {}
};
class AguiTimedEvent {
std::auto_ptr<AguiEvent> event;
double timeSec;
AguiWidgetBase* caller;
public:
AguiTimedEvent(std::auto_ptr<AguiEvent> ev, double time, AguiWidgetBase* base)
: event(ev)
, timeSec(time)
, caller(base) {}
void call() { event->Call(); }
// All the rest of it
};
void MakeIt() {
class someclass : AguiEvent {
bool MahBool;
public:
someclass() { MahBool = false; }
void Call() {
// access to MahBool through this.
}
};
something->somefunc(AguiTimedEvent(new someclass())); // problem solved
}