阵列内存分配不工作 [英] Array memory Allocation doesn't work

查看:135
本文介绍了阵列内存分配不工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有下面的课程:

  A类{
}

class B:public A {
int num;
};

在我的主要有:

  int main(){
A * vec; // A是一个带有纯虚函数的类
vec = new B [2]; //想创建一个向量B
}

vec [0] ,但vec [1]为NULL。为什么没有给我分配合适的记忆?



我不想改变主线。



(我知道我可以把main改成:B * vec = new B [2]但我不想要)


解决方案

不能以多态方式处理数组,C ++语言不支持它。表达式 vec [x] 使用指针算术来确定元素的位置。如果你通过一个基类指针访问它,如果对象的大小以任何方式变化将不会工作。



例如,你的基类是4字节大小,子类大小为8字节。

  base * a = new child [4] 

当您访问 a [1] 编译器使用基类的大小计算偏移量。在这种情况下,偏移量为4个字节,最后指向第一个元素的中间。



我建议使用 std :: vector std :: array 的指针。

  //对于需要调整大小的数组(需要为每个新的删除)
std :: vector< A *> vec(5,NULL);
for(int i = 0; i< vec.size(); i ++)
{
vec [i] = new B();
}

//对于大小固定的数组(每个新需要删除)
std :: array< A *,5> vec;
for(int i = 0; i< vec.size(); i ++)
{
vec [i] = new B();
}

//对于用智能指针固定大小的数组
//不需要删除
std :: array< std :: unique_ptr< A> ,5> vec;
for(int i = 0; i< vec.size(); i ++)
{
vec [i] .reset(new B());
}


I have the next classes:

class A {
};

class B : public A {
  int num;
};

in my main I have:

int main() {
    A* vec; // A is a class with pure virtual functions
    vec = new B[2]; // want to create a vector of B
}

vec[0] is defined correctly, but vec[1] is NULL. why didn't it allocate me a fit memory?

I don't want to change the lines of the main. just make it working.

(I know I can change the main into: B* vec = new B[2] but I don't want)

any help appreciated!

解决方案

You cannot treat arrays polymorphically, the C++ language does not support it. The expression vec[x] uses pointer arithmetic to determine the location of the element. If you are accessing it through a base class pointer it will not work if the size of the objects vary in any way.

For example, you have base class that is 4 bytes in size and the subclass is 8 bytes in size.

base *a = new child[4];

When you access a[1] the compiler calculates the offset using the size of the base class. In this case the offset is 4 bytes which ends up pointing to the middle of the first element.

I recommend using a std::vector or std::array of pointers with an appropriate smart pointer.

// For arrays that needs to be resized (requires delete for each new)
std::vector<A*> vec(5, NULL);
for(int i = 0; i < vec.size(); i++)
{
    vec[i] = new B();
}

// for arrays that are fixed in size (requires delete for each new)
std::array<A*, 5> vec;
for(int i = 0; i < vec.size(); i++)
{
    vec[i] = new B();
}

// for arrays that are fixed in size with smart pointers
// no delete needed 
std::array<std::unique_ptr<A>, 5> vec;
for(int i = 0; i < vec.size(); i++)
{
    vec[i].reset(new B());
}

这篇关于阵列内存分配不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆