数组内存分配不起作用

时间:2013-05-16 13:56:54

标签: c++ memory-management polymorphism pointer-arithmetic

我有下一个课程:

class A {
};

class B : public A {
  int num;
};

在我的主要内容中我有:

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]定义正确,但vec [1]为NULL。为什么不给我一个合适的记忆?

我不想改变主线。只是让它工作。

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

任何帮助表示赞赏!

3 个答案:

答案 0 :(得分:5)

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

例如,您的基类大小为4个字节,子类的大小为8个字节。

base *a = new child[4];

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

我建议使用带有适当智能指针的std::vectorstd::array指针。

// 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());
}

答案 1 :(得分:1)

如果你希望它是多态的,只需创建一个指针数组

new A*[array_size]

答案 2 :(得分:0)

此代码段说明了您遇到的问题。

#include <iostream>
using namespace std;
class A {
};

class B : public A {
  int num;
};

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

    cout << sizeof(vec) << endl;
    cout << sizeof(*vec) << endl;
    cout << sizeof(vec[2]) << endl;
    cout << sizeof(new B()) << endl;
}

在指针算术中,您分配的指针类型的大小是用于递增的大小,而不是它指向的对象的真实类型的大小。更简单地说,该语言不支持多态数组。这只是对原因的解释。