c++ - initialize object array on the heap

Follow our previous discussion of how to initialize the object array in this post - c++ - object array intializer in c++ , We said that the if we use the new operator to allocate objects array on the heap, there is no way to do the initialization except for the default constructors, well, here is some tricks that you can do to make the objects array allocated on the heap to have the non-default constructor called. 

 

the trick is to use the placement new operator.  (you may refer to this post - c++ - a sample class to show common aspects of object initialization/uninit on the definition of Account class, you  may need to add yet another memer methods).

 

here is the code. 

 

 

/**
* file 
*   heap_array_initializer.cpp
* description: 
*   THis shows some way to initialize an array of classes in the heap 
*/

#include "stdafx.h"
#include "acct.h"
#include <iostream>
#include <cstddef>
#include <new>  // include this header to use the placement new operator.
#include <utility> // what willl use use this for? abort()???
#include <vector>

using std::cout;
using std::endl;
using std::cerr;
using std::vector;
using std::pair;

typedef pair<char *, double > value_pair;

/** init_heap_array() 
*
*  declared as a static member function
*  provides for allocation and initialization
*  of heap array of class objects
*  init_values: init value pair for array elements
*  elem_count: number of elements in array if 0, array is size of init_value vector
*/

Account * 
	Account::init_heap_array(vector<value_pair> &init_values, 
	vector<value_pair>::size_type elem_count = 0) 
{

	vector<value_pair>::size_type vec_size = init_values.size();

	if (vec_size == 0 && elem_count == 0) { 
		return 0;
	}

	// size of the array to allocate is either elem_count 
	// or, if elem_count is 0, the size of vector..
	size_t elems = elem_count ? elem_count : vec_size;

	//grab a chunk of raw memory to stoe array
	char * p = new char [sizeof(Account) * elems];

	// individuallky initialize each array elements
	int offset = sizeof(Account);
	for (int ix = 0; ix < elems; ++ix) {
		// offset to the ixth elements,
		// if an initial value pair is provided
		//   pass that pair to the constructor
		// otherwise, invoke the default constructor 
		if (ix < vec_size) { 
			new (p+offset * ix) Account(init_values[ix].first, init_values[ix].second);
		}
		else new (p+offset * ix) Account;
	}

	// ok: elements allocated and initialized
	//    retur pointer to first element
	return (Account *) p;

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值