我目前正在研究动态内存容器。
该类的基本思想是,如果你真的不知道它,你应该能够获得一个对象的迭代器,而不是在所有元素中使用for循环来提高性能。我的问题如下:当您将指针地址传递给要获取其迭代器的对象时,将对象强制转换为扩展内存容器结构类型。此类型包含一个额外元素,一个整数。 (IteratorNum)
当跟随代码时,函数中的整数被设置为正确的值,如下所示。但是当返回的值被设置为main函数中使用的局部整数时,它是200?我一直在添加手表,无法弄清楚该函数如何返回50但值设置为200.
template <typename DataType> class MemoryContainer {
public:
struct LevelData : DataType
{
int element;
};
DataType &New()
{
elements++;
//Reallocate the size of the array
ld = (LevelData*)realloc(ld, sizeof(LevelData) * elements);
//Set the iteratorNumber
ld[elements - 1].element = elements - 1;
return ld[elements - 1];
}
DataType *reserve(int num)
{
return calloc(num, sizeof(DataType));
}
DataType &operator[](int i)
{
return ld[i];
}
bool inArray(DataType *type)
{
//Compare memory addresses and see if it's within.
return (type >= &ld[0]) && (type < &ld[elements - 1]);
}
static unsigned int getIterator(DataType *type)
{
// v this is 50, but in main says returns 200.
return ((LevelData*)type)->element;
}
MemoryContainer()
{
elements = 0;
}
~MemoryContainer()
{
free(data);
}
private:
unsigned int elements;
LevelData *ld;
};
struct Effective
{
//Set it to polymorphic classes
virtual void dummy()
{
}
char * testvar;
Effective(char * c)
{
testvar = c;
}
Effective(){}
};
MemoryContainer<Effective> myContainer;
int _tmain(int argc, _TCHAR* argv[])
{
//Create 200 elements in the array
for(int i = 0; i < 200; i++)
myContainer.New().testvar = "E";
//Add pointer for testing purposes to get the iterator.
Effective * pointer = &myContainer[50];
//Test setting it's value
pointer->testvar = "HEHEHE";
//Get iterator of our pointer in the array
unsigned int i = myContainer.getIterator(pointer);
printf(pointer->testvar);
system("PAUSE");
return 0;
}
答案 0 :(得分:1)
我怀疑是Visual Studio调试器在你的两个i
变量之间混淆了。如果您打印出i
的值,它将正确打印。如果将变量的名称更改为其他名称,则调试器中的值显示为50.
也就是说,你的代码是c和c ++的混合代码,并且无法正常处理任何需要复制构造函数的东西。我建议至少使用new []
而不是realloc
。
此外,此集合中任何试图存储名为element
的成员变量的类的用户都会变得非常困惑。
答案 1 :(得分:1)
main函数中的unsigned int i的值确实为50,但是调试器将它与for循环中声明的i混淆(我用Visual Studio 2013重现了这一点)。如果你cout我将是50,如果你更改变量名称它将在调试器中显示为50。我之前从未见过这个问题,所以我想知道是否可能是因为你使用了malloc / realloc / free和C ++对象。