casting a pointer in Run Time [non-trivial Scnerio] - c++

I have to fix a typical memory leak, Problem is like that :
typedef std::map<unsigned long,Response> mapType;
class Response
{
public:
void *dataPtr;
unsigned long tag;
}
class anyClass
{
public::
DataType x;
}
From client i am getting a map of Type mapType , Which has Response object as map->second , As Response object contain a void Pointer.
Please note : Response Class do not know what type of data has been set to void pointer, Also i can't modify Response class to do so , As it is a legacy code and has a great impact :(
Now using map->first ,that i call as Tag,
Using this tag at run time using this tag i come to know about a class anyClass.
Now Response::dataPtr is smae as anyClass::DataType
But:
as class anyClass is one out of N type, So anyClass::DataType differs for each class which i come to know only at runtime.
Please guide me how i can cast a void pointer to type same to anyClass::DataType and can free it

Given that you mention "legacy" code, but may have some freedom to modify, I would likely suggest that whatever interface provided you the map be extended to include a free-ing function.
Then it could apply the same type logic as when it created the object in the first place.
If that is impossible, then you will likely end up with a case statement and some re-interpret casts like the following pseudo-code:
switch (type ) {
case Type1:
delete reinterpret_cast<Type1Class*>(ptr);
break;
case Type2:
...
Good Luck

First, I don't know why do you need to cast these pointers to their original type if it is a memory leak issue. You can simply delete the void* pointer anywhere.
Second, you can convert the pointer to a specific type with a simple conditional statement to some specific type compared to the tag, but you need to have the specific code for that pointer in the given context, so in this sense there is not enough information here to solve the problem.
However, if you have a certain behaviour for your responses, call it 'process', you can use inheritance with virtual function to bind the desired behaviour to your object. This is basically the definition of the virtual methods, so use them, even if you need to refactor the old code for this. If there is a problem with the object disposing then it is a matter of a virtual destructor, so the base class should define a virtual dtor, and the using the dynamic_cast(ptr) gives you some type safety at the conversion.
In this way, you don't need the 'tag' member, unless you would like to this by hand with a big 'switch' statement. In this case I can suggest to use crc calculation from the typeid(AnyClass).name() in the tag member.
-- EDIT:
There is an other way to store these object without having this issue, I would say a boost::any or similar functionality could solve your problem. If you are storing the data's in a boost any instead of void* pointers you can change the legacy code with a minimal impact. If you delete an entry from the map, it will remove the boost::any's inner value. That should do the trick.

If your tags are sequential you can build smth. like an array with either function objects or function pointers of their handlers:
template<class T>
void deleteType(void* p)
{
delete reinterpret_cast<T*>(p);
}
typedef void (deletePtr)(void*);
deletePtr handlers_[] =
{ &deleteType<int> //means: accessed by tag with value 0
, &deleteType< vector<int> > // tag with value 1
, ...
};
//somewhere later:
handlers_[response->tag](response->dataPtr);
This solution requires you to know all types which are possibly stored in response.
If tags are not sequential, you will need to use a map or smth. similar, which involves non-constant complexity.
Hope that helps,
Ovanes
P.S. But if you decide to change the response take a look at boost::variant. Which is exactly what you need, if you were allowed to program generically ;)

Related

How can I create a C++ class that accepts function pointers with different signatures?

I am relatively new to C++ and I am working on a personal project for practicing where I need to create a class that can take function pointers with different signatures.
The idea is that each instance of the class will store a pointer to a specific function and can call that function whenever I want.
To give a better idea of what I want, let me explain with a little bit more detail what I am trying to do. The project I am working on is a very basic console game and the object I am trying to create is an object that would store details on each location the player can access in the game.
(DISCLAIMER: I know that most of what I describe later is probably an overkill for a basic console game. I can easily make the whole game in a couple of files using just simple functions and I know how to do that. But the idea here is that I wanted to practice more advanced C++ techniques without having to figure out a complex project. So, since I know how to make a basic console game, I thought it would be a good idea to try and figure out how to achieve the same result but with more advanced techniques)
One of the details that I think should be stored is what happens in each location, basically the text that is output to the screen describing what happens and prompting the user to take action.
Since this would be different for each location, I can't just declare and implement a function in the class.
One way of solving this issue is to create a base class with a virtual function and then implement this function in a series of derived classes, each defining a new location.
The problem I have with this approach is that it makes each location a class that can be inherited further and instanced, which I don't need as I will only have 1 instance of each location.
I can of course just create 1 instance of the class, but I wanted to see if there is a way to avoid having to create separate classes for each location.
This why I started thinking of function pointers.
Now, I know I can declare a function pointer and initialise it in a class like that:
class Test
{
public:
Test(void (*p)())
: print{p}
{}
private:
void (*print)();
};
That works fine as long as the function returns void and accepts no arguments.
So, I thought maybe I can do that with a template:
template <typename Function>
class Test
{
public:
Test(Function *p)
: print{p}
{}
Function *print;
};
This actually works well. I can now have a class that accepts different functions with different return types.
I can create instances of the class in the following way:
void print();
Test<void ()> a {print};
However, I have one problem with this approach. Because it is a class template, I can't have a pointer that I want to use to point to instances of Test class regardless of the function that is passed to them.
For instance, if I declare the following pointer:
Test<void ()> *b = &a;
There is no way to re-assign that pointer to another instance of Test class unless the function pointer passed to it also returns void and accepts no arguments. Otherwise, I have to create a new pointer.
Is there a way to avoid that? Is there a better way of achieving what I am looking for than using function pointers?
Thank you very much and sorry for the long message.
There is no way to re-assign that pointer to another instance of Test class unless the function pointer passed to it also returns void and accepts no arguments.
And how would you expect that to work? Each Test has a different signature for its print method. In the example below, if you assigned action2 to action1, then how would it know what to pass to the print function?
void fun1() {}
void fun2(int) {}
void test() {
Test<void()> action1= &fun1;
action1.print();
Test<void(int)> action2= &fun2;
action2.print(42);
}
What you want is really simple, thanks to improvements in C++11: std::function<void()>.
Whenever you need to pass some arguments to the function, you'd use a lambda, potentially with captures:
#include <functional>
void fun1() {}
void fun2(int) {}
using Action = std::function<void()>;
int main() {
class MyObject { public: void doSomething() {} } obj;
Action action1;
action1 = fun1;
action1 = []{ fun2(42); };
action1 = [&obj]{ obj.doSomething(); }; // obj captured by reference
}
So that's pretty much what you should do.
Now of course you may ask "hey, but what if I wanted to implement something like std::function myself"? It's not a trivial task, if you want to get full functionality of std::function, including small object optimization (i.e. std::function usually doesn't allocate unless the functor it wraps is "big").
I wanted to see what can I do if I had a reason to have the each game location using a function that have different return types.
You chose to use a common abstraction, i.e. some class (like Action) that you can always call the same way, and get to do various things. So, what would you like the following code to do?
Action someAction;
int result = someAction();
std::string result = someAction();
Now suppose that e.g. someAction has captured a void() function. What should the code that assigns the "result" to an integer or a string do? And how would you protect from mistakes, e.g. if you really wanted someAction() to return an int, but you accidentally used one that returns nothing?
Remember that the compiler has to generate code for all of the sites where you call someAction, so it needs to know what to do ahead of time, even if you may otherwise ensure that no "incorrect" calls are made.
You could implement a custom Action class on top of std::function that could support std::optional<ResultType> instead of ResultType. That way, if the actual result of the functor wrapped in Action was convertible to that ResultType, you'd get a non-null optional, otherwise the optional would be null. And the list of supported result types would need to be pre-determined, i.e. the compiler wouldn't be able to dynamically add them, but adding a new type should amount to passing an additional type as a template argument, so it'd be easy to support quite many types.

void*, extension and template. pros and kontras

Sometimes I have a problem and see 3 ways of implementing the solution. I want to know when to use which of these 3 different implementations. Below there are some exsamples, to see what I mean. I also wrote some pros/kontras which I think is correct. If something seems to be wrong, then please tell me and I'll change that.
void* example:
void method(void* value)
{
//save value as member
}
pro void*:
void* can save every type and you don't have to use templates (in headers).
kontra void*:
-when you have a list of void* you can store in index[1] another type than in index[2] which is critical, because you don't know which type it is. But with dynamic_cast you can check if you can cast it to the type or not.
-when you have a void* list with entities of the same class which have 2 variables, you can not sort by variable1 / variable2 without casting it back to the original class.
Extension exsample:
Creating a new class and extent it on another class:
class CTestClass
{
void Method1();
};
class CTest2 : CTestClass
{
//use somehow the method
};
std::vector<CTestClass> list;
pro Extension:
this way of implementing a class can be usefull, if you need a method which is in every object you need. For example you want to sort by a variable. In such a method you can make the compare.
kontra Extension:
much effort
exsample template:
template <class T>
class CTest
{
//do some stuff
};
pro template:
in a template list, you can not add different types at the same time.
kontra template:
when you have a template list of type T and T has for exsample 2 variables. You can not say: sort by variable1 or variable2 because you can not get into the class T.
As far as I know: you have to implement the template into the header file, which is ugly to see.
I hope everyone understands what I mean.
Is void* a good way to program?
Can I write templates also in .cpp files?
What do you think when to use which of this techniques? Is there some kind of rule?
The statement below is incorrect
pro void*:
void* can save every type and you don't have to use templates (in
headers).
Templates haver their closest equivalent in cross macros and not in void pointers, but exist for a different set of purposes than the mere polymorphism afforded by void pointers. Using void pointers in no way substitutes templates.
While modern programmers might not recommend about using void pointers, complaining about the (true!) potential dangers afforded, old school C-style code certainly has a use for them and this is the reason they exist. Pairing the benefits gained from void pointers with the tradeoff in performance by the C++ dynamic cast, would simply spoil the choice.
Void pointers just exist to offer limitless flexibility at managing memory when you know what you are doing and should be used only in that case. There is no comparison between them and templates.
A method that takes a void * argument should only exist when:
Case 1: The size of the passed data is known and the argument is considered as raw data. It makes no difference what that data is.
Case 2: The size of the passed data is known and you plan to convert it to a pointer of the appropriate type later (for example by some parsing, enumeration policy, known type, etc) but in order to go through some general purpose functions, libraries, APIs, you must convert it to known-length void* inbetween.

dynamic_cast or redundancy?

In my system low hiearchy objects talk to the high hiearchy object via calling function of the +1 level hiearchy object, which calls a function of the +1 level hiearchy object, etc etc etc, until the function calling stops at the recipent.
There is a Message abstract class, and there are lots of derivated classes, which hold different kinds of datas.
Like:
FruitMessage: string, int
CoordinateMessage: float, float, float
etc etc
And those methods I mentioned before want Message objects so this chaincalling is done through one kind of method instead of creating methods for all of the Message types.
The problem comes, when the recipent receives the Message object.
The recipent wants to know what's in that message, so it can process receives message as the message type requires it.
(like it decreases the integer by 1 in FruitMessages, divides the coordinates in CoordinateMessages, etc.)
Currently I have two ideas, but maybe none of them is correct and I should use a third one. (tell me please)
The recipent dynamic_casts it while it doesn't the correct type.
Message has an enum field called MessageType, which is initalized in the derived class' constructor to the correct value, so the recipent just uses a switch-case during the process.
My question is that is it worth the redundancy?
dynamic_cast is slower than the integer check
but every time I create a new Message class I have to create a new enum value.
What should I do?
Both ways are OK. Redundancy vs speed is very common problem in Software development.
I would choose dynamic_cast as redundancy is the first step to bugs, but it's really up to you and depends on your performance requirements.
I saw very similar problem while working with Akka, they usually use dynamic_cast (I mean java/scala analogues)
I would recommend using the typeid operator to check the type of the message. This way, you avoid repeatedly calling dynamic_cast until you get the correct type.
void process_message(Message const& msg) {
if (typeid(msg) == typeid(FruitMessage)) {
auto& fruit_msg = static_cast<FruitMessage const&>(msg);
…
}
}
Even better, you could use the C++17 std::any container type. An any object can be copied around like a non-polymorphic value, and does not require the use of a virtual base class. If you don't have access to a C++17 library implementation, you could use boost::any instead.
void process_message(std::any const& msg) {
if (msg.type() == typeid(FruitMessage)) {
auto fruit_msg = std::any_cast<FruitMessage>(msg);
…
}
}
As for whether using an enum field would be faster than typeid or any, you'll have to do the benchmarking yourself.

Align A Pointer To Have A Functional -> Operator? C++

This quesiton is composed of a couple parts, the first has to do with the -> operator in a class. Does it take some sort of input (according to the C++ standard)? For example
some_return_type? operator->( long address ) {
cast the address to some sort of pointer and do something with it...
return something?...possibly... maybe not?;
}
So in reality A::SomeMethod() would refer to an address for a function in memory passed to ->. Or
A::someStaticOrNonStaticDataMember would refer to an address for a field?
If so (given that we do not have access to the actual type of the class), or something like this exists, what is it, and can we reconstruct part of a pointer, or align a pointer, (or write a class with an algorithm to do this), for a class based on some information about that class, so that it had an operable -> operator, so one could write:
somePointer->A::SomeMethod();
and have it call A::SomeMethod()? And maybe make context for the memory used in the class?
From the comments it seems you want to control how Compiler handles and generates -> tokens. This is for your bad luck not possible, because Compiler doesn't expose such information, nor is it required by Standard to do so
It is like you are trying to have "dynamic" (the C# type) but in C++, unluckily this is not possible. What could be similiar is wrapping some sort of "Closure collection" addressed by strings (a sort of scripting language) but that would be really heavy and not very nice.
Actually doing what you want with the syntax you showed is not possible.
If the type of an object is not known, then you have that object hided behind a "void *". That means basically that the only way you can use that object is by casting it back to its original type.
Suppose you have a DLL that expose 2 functions (with header files)
// creates an object of given type or null_ptr if no object match
void* getObject(std::string obj_type);
// call a method on that object
void callMethod(void* obj, std::string method_name, void* args, void* returnval);
Actually that solution (even if ugly) allows to call methods on objects that you don't know (it could be a lot better than that.)
But that force you to use void* and strings. That's because how C++ resolve method names (in reality also in C# the "dynamic" type generates behind the scenes reflection code that use strings with method names and is particulary slow)
So something similiar can be achieved with
float fuelLiters = 3.0f;
void * myObj = createObject("SomeCar");
callMethod(myObj,"loadFuel", &fuelLiters, null_ptr);
you probably can make the syntax a little better with templates or some macro, but you'll never be able to do something like
myObj->A::loadFuel(fuelLiters);
What you can do is having the externally loaded class, use the same interfaces of your application, says:
class ICar{
public:
void loadFuel(float liters)=0;
};
In that case you can use a function that cast the opaque object handle to ICar. This is what I already doing in a library I wrote 2 years ago:
So you just need the DLL expose a method for casting the class (downcast)
//if given object is implementing a ICar, the correct pointer is returned, else
// this function will return nullptr (or throw exception if you like more)
void * downcast( typeof(ICar), myObj);
You'll need simply
ICar *myCar = static_cast<ICar>(downcast( typeof(ICar), myObj));
myCar->loadFuel(3.0f);
However note that both the DLL and your application should "know" about what "ICar" is, so they must include the "ICar" header.
doing that is definitely possible, I did it already in 2 different ways, so If you need more details about implementation I'll be happy to show a possible way (given I understood correctly your question).
The arrow operator (->) is a dereference operator that is used exclusively with pointers to objects that have members.
foo->bar() is the same as (*foo).bar()
If you want to overload -> you should also overload *

Alternate ways to identify polymorphic objects?

I've been searching all through the web and I seem to not find any alternate way of doing comparing if two polymorphic objects are the same type, or if a polymorphic object IS a type. The reason for this is because I am going to implement a Entity System inside of my game that I am currently creating.
I have not found another way of doing this other than with the use macros or a cast (the cast not being a portable method of doing so). Currently this is how I am identifying objects, is there a more efficient or effective way of doing this? (without the use of C++ RTTI)
I pasted it on pastebin, since pasting it here is just too much of a hassle.
http://pastebin.com/2uwrb4y2
And just incase you still do not understand exactly what I'm trying to achieve, I'll try to explain it. An entity in a game is like an object inside of the game (e.g. a player or enemy), it have have components attached to it, these components are data for an entity. A system in the entity system is what brings the data and logic of the game together.
For example, if I wanted to display a model up on the screen it would be similar to this:
World world; // Where all entities are contained
// create an entity from the world, and add
// some geometry that is loaded from a file
Entity* e = world.createEntity();
e->add(new GeometryComponent());
e->get<GeometryComponent>()->loadModel("my_model.obj"); // this is what I want to be able to do
world.addSystem(new RenderingSystem());
// game loop
bool isRunning = true;
while(isRunning)
{
pollInput();
// etc...
// update the world
world.update();
}
EDIT:
Here's a framework, programmed in Java, that does mainly what I want to be able to do.
http://gamadu.com/artemis/tutorial.html
See std::is_polymorphic. I believe boost has it too.
If T is a polymorphic class (that is, a class that declares or inherits at least one virtual function), provides the member constant value equal true. For any other type, value is false.
http://en.cppreference.com/w/cpp/types/is_polymorphic
Edit:
Why can't you just do this in your example?
Entity* e = world.createEntity();
GemoetryComponent* gc = new GeometryComponent();
gc->loadModel("my_model.obj");
e->add(gc);
Create the structure before stripping the type information.
If you're determined not to use C++'s built-in RTTI, you can reimplement it yourself by deriving all classes from a base class that contains a virtual method:
class Base {
public:
virtual string getType() = 0;
};
Then every derived class needs to overload this method with a version that returns a distinct string:
class Foo : public Base {
public:
string getType() { return "Foo"; }
};
You can then simply compare the results of calling getType() on each object to determined if they are the same type. You could use an enumeration instead of a string if you know up front all the derived classes that will ever be created.
Entity* e = world.createEntity();
e->add(new GeometryComponent());
e->get<GeometryComponent>()->loadModel("my_model.obj");
// this is what I want to be able to do
First the simple: there is a base type to all of the components that can be added, or else you would not be able to do e->add(new GeometryComponent()). I assume that this particular base has at least one virtual function, in which case the trivial solution is to implement get as:
template <typename T>
T* get() {
return dynamic_cast<T*>(m_component); // or whatever your member is
}
The question says that you don't want to use RTTI, but you fail to provide a reason. The common misundertandings are that RTTI is slow, if that is the case, consider profiling to see if that is your case. In most cases the slowness of dynamic_cast<> is not important, as dynamic_casts should happen rarely on your program. If dynamic_cast<> is a bottleneck, you should refactor so that you don't use it which would be the best solution.
A faster approach, (again, if you have a performance bottleneck here you should redesign, this will make it faster, but the design will still be broken) if you only want to allow to obtain the complete type of the object would be to use a combination of typeid to tests the type for equality and static_cast to perform the downcast:
template <typename T>
T* get() {
if (typeid(*m_component)==typeid(T))
return static_cast<T*>(m_component);
else
return 0;
}
Which is a poor man's version of dynamic_cast. It will be faster but it will only let you cast to the complete type (i.e. the actual type of the object pointed, not any of it's intermediate bases).
If you are willing to sacrifice all correctness (or there is no RTTI: i.e. no virtual functions) you can do the static_cast directly, but if the object is not of that type you will cause undefined behavior.