OMNeT++ Simulation Library  6.0.3
any_ptr Class Reference

#include <any_ptr.h>

Description

A type-safe equivalent of the void* pointer.

any_ptr accepts a pointer of any type, and keeps the memory address along with the pointer's type. The pointer can be extracted from any_ptr with the exact same type it was used to store it. This was achieved with the use of template methods, typeid() and std::type_info.

The primary use of any_ptr is with cClassDescriptor.

IMPORTANT: Since std::type_info knows nothing about inheritance relationships, any_ptr cannot perform any upcast or downcast when extracting the pointer. The following code snippet raises a runtime error:

cMessage *msg = new cMessage();
any_ptr ptr = any_ptr(msg);
cObject *obj = ptr.get<cObject>(); // ==> "Attempt to read any_ptr(cMessage) as cObject*"

When casting is important (~always), the toAnyPtr()/fromAnyPtr() functions should be used for converting an object pointer to and from any_ptr. Most toAnyPtr()/fromAnyPtr() functions are generated by the message compiler from .msg files.

Updated code snippet:

cMessage *msg = new cMessage();
any_ptr ptr = toAnyPtr(msg);
cObject *obj = fromAnyPtr<cObject>(ptr); // works as expected

The documentation for this class was generated from the following file: