I was looking through some of the articles here on gamedev.net and I stumbled upon this code:
namespace nTreeData
{
const int kMaxLeaves = 10;
const int kMaxDepth = 5;
}
class Leaf
{
public:
Leaf() : value_(0) {}
explicit Leaf(const int &value) : value_(value) {}
const int &value() const { return value_; }
bool operator==(const Leaf &rhs) const
{ return this->value() == rhs.value(); }
bool operator<(const Leaf &rhs) const
{ return this->value() < rhs.value(); }
private:
int value_;
};
#include <map>
#include <iostream>
typedef std::map<Leaf, int> LeafMapConcrete;
typedef std::map<Leaf, int>* LeafMapPointer;
typedef std::map<Leaf, LeafMapPointer > LeafMap;
void fun()
{
using namespace nTreeData;
LeafMap leafTree;
////////////////////////////////////////////////////
// create a simple leaf tree
////////////////////////////////////////////////////
for (int i = 0; i < kMaxLeaves; ++i)
{
// insert a starter leaf
LeafMapPointer p = new LeafMapConcrete;
leafTree.insert(LeafMap::value_type(Leaf(i), p));
LeafMap::iterator iter = leafTree.find(Leaf(i));
// continue inserting children inside of children
for (int depth = 0; depth < kMaxDepth; ++depth)
{
LeafMapPointer inner = new LeafMapConcrete;
LeafMap* outer = (LeafMap*)(iter->second);
outer->insert(LeafMap::value_type(Leaf(depth), inner));
iter = outer->find(Leaf(depth));
}
}
////////////////////////////////////////////////////
// deallocate the leaf tree
////////////////////////////////////////////////////
for (LeafMap::iterator destroy = leafTree.begin();
destroy != leafTree.end();
++destroy)
{
LeafMap::const_iterator inner = destroy;
LeafMap* iterMap = (LeafMap*)(destroy->second);
LeafMap* lastMap;
for (inner = iterMap->begin(); inner != iterMap->end();
inner = iterMap->begin())
{
lastMap = iterMap;
// move the iterMap forward
iterMap = (LeafMap*)inner->second;
delete lastMap;
}
}
}
My question is what exactly is happening when one type casts LeafMapPointer to pointer to LeafMap? Insert is called on the converted pointer and it seems that one can insert a Leaf and a pointer even though the class that LeafMapPointer points to (LeafMapConcrete) takes a Leaf and an int? I have also seen this code:
int x;
char* p = &x;
char[0] = 0xff;
char[1] = 0x01;
char[2] = 0xa3;
char[3] = 0xbb;
I believe what is happening here is that the int is being assingned byte by byte.
Any help is appreciated. Thanks.
xidis