使用“new”后添加新对象

时间:2011-01-18 17:09:39

标签: c++ pointers object new-operator

在我调用new之后,如何向指针添加更多对象? (我需要一堂课) 这就是我的意思:

int *a;
a = new int;
a = new int;

非常感谢!

4 个答案:

答案 0 :(得分:3)

您应该使用vectorlist

答案 1 :(得分:2)

在C中,您将使用realloc。在C ++中,您将使用STL的std::vector而不是指针。你总是可以做一些丑陋的事情:

int *a;
a = new int[1];
delete [] a;
a = new int[2];

但是你的性能下降了。

答案 2 :(得分:0)

如果你需要一个连续的缓冲区使用向量。

std::vector<int> buf;
buf.push_back( 1 );
buf.push_back( 2 );
buf.push_back( 3 );

int * intbuf = &buf[0];

如果向向量添加更多项目,请注意此指针可能无效。如果您想要首先执行此操作,可以阻止此操作:

buf.reserve( 65536 );

或其他一些号码。您仍然可以向矢量添加超过65536个项目但保证只要大小小于此值,&amp; buf [0]就不会改变。

鉴于你没有做任何这个,你试图实现向量,一种方法是不使用new,而是使用malloc来分配内存,因此:

char * buf = static_cast<char *>( malloc( BUF_SIZE ) );

现在,您可以使用展示位置

在此处创建对象
int * intbuf = new( buf + sizeof(int) * N ) int( i );

当您需要更多空间时,您可以“重新分配”您的指针。确保首先重新分配给临时的,以检查它是否成功。

bufNew = static_cast< char * >( realloc( buf, newBufSize ) );
if( bufNew )
     buf = bufNew;

这可以在这里工作,因为int是POD类型。如果类型不是POD,则重新分配并简单地按内存移动对象是不安全的,您需要将它们作为对象移动,每个都使用operator =。

现在你对此有所了解,但出于实际目的,你可能想要使用vector。

答案 3 :(得分:0)

听起来你正在尝试编写自己的矢量类,可以按需增长。您可以按如下方式执行此操作:

int * a; // original pointer
a = new int[5]; // just five elements

现在将它增长到10个元素(创建一个新数组,复制旧内容,回收旧数组的内存,并重新分配数组指针):

int * tmp = new int[10]; // a new array
memcpy (tmp, a, 5 * sizeof(int)); // copy the old items into the new array
delete [] a; // reclaim the memory from the old array
a = tmp; // reassign a to point to the new, bigger array

有关此类“动态表格”的说明和分析,请参见Cormen, Leiserson, Rivest and Stein,第17.4章。