【C++】C++对象数组的定义和初始化
⽬录
即看即⽤
⼀、赋值初始化
1、如果类有默认构造函数
object *p = new object[3];
2、如果类没有构造函数
没有默认构造函数,有⾃定义的构造函数 object(contx* c,stack* s)
object *p = new object[3]{{cct,this},{cct,this},{cct,this}};
(但这个要求object构造函数前不能有explicit,否则⽆法将{cct,this}隐式转换成object)
object *p = new object[3]{object(cct,this),object(cct,this),object(cct,this)};
(但这个要求object有object::object(const object&)构造函数,否则报错: error use of deleted function)
实例
#include <iostream>
using namespace std;
class Acct
{
public:
// Define default constructor and a constructor that accepts
//  an initial balance.
Acct() {
balance = 0.0;
cout << "no " <<  endl;
}
Acct( double init_balance ,double init_cc ) {
balance = init_balance;
cc = init_cc;
cout <<  "with " << endl;
}
~Acct(){
cout <<  "" << endl;
}
private:
double balance;
double cc;
};
int main()
{
//栈中创建对象数组
Acct myAcct[6];
//堆中创建对象数组
Acct *CheckingAcct = new Acct[3];
Acct *SavingsAcct  = new Acct[3] {Acct(34.98,2), Acct(131.4,2), Acct(521.1,2)};
Acct *SavingsAcct2 = new Acct[3] {{34.98,2}, {131.4,2}, {521.1,2}};
delete [] CheckingAcct;
delete [] SavingsAcct ;
// ...
}
⼆、⽤指针数组
typedef  Acct* ACCP; //ACCP是个指向EquipmentPiece的指针
ACCP bestPieces[10]; //等同于 ACCP *bestPieces = new ACCP[10];
//然后初始化 for(int i = 0; i < 10; i++){ bestPieces[i] = new Acct(balance ,cc ) ; }
注意:要记得将此数组所指的所有对象删除。如果忘了会产⽣资源泄露。还有就是该⽅法与对象数组相⽐需要额外内存⽤于存放指针。(过
度使⽤内存这⼀问题可以避免,见第三种⽅法)
三、上⾯的只适合静态数组,动态数组⽤C++11的allocator 对于allocator类,请看另⼀篇blog
请看⼀下代码关于使⽤如何实现⽆默认构造函数,动态实例化对象数组的allocator⽅法
//#include "CAnimal.h"
#include <memory>
#include <iostream>
using namespace std;
class Animal
{
public:
#if 0        //即使为0,没有默认构造也是可以,
Animal() : num(0)
{
cout << "Animal constructor default" << endl;
}
#endif
Animal(int _num) : num(_num)
{
cout << "Animal constructor param" << endl;
}
~Animal()
{
cout << "Animal destructor" << endl;
}
void show()
{
cout << this->num << endl;
}
private:
int num;
};
/*
由于allocator将内存空间的分配和对象的构建分离
故使⽤allocator分为以下⼏步:
1.allocator与类绑定,因为allocator是⼀个泛型类
2.allocate()申请指定⼤⼩空间
4.使⽤,与其它指针使⽤⽆异
5.destroy()析构对象,此时空间还是可以使⽤
6.deallocate()回收空间
*/
int main()
{
allocator<Animal> alloc;        //1.
Animal *a = alloc.allocate(5);    //2.
/
/3.
/*void construct(U* p, Args&&... args);
在p指向的位置构建对象U,此时该函数不分配空间,pointer p是allocate分配后的起始地址
constructor将其参数转发给相应的构造函数构造U类型的对象,相当于 ::new ((void*) p)
U(forward<Args> (args)...);
*/
/
/4.
a->show();
(a + 1)->show();
(a + 2)->show();
(a + 3)->show();
(a + 4)->show();
//5.
for (int i = 0; i < 5; i++)
{
alloc.destroy(a + i);
}
/
/对象销毁之后还可以继续构建,因为构建和内存的分配是分离的
//6.
alloc.deallocate(a, 5);
<();
return 0;
}
如果构造函数是多个参数,则可以这样:
//3.
#include "allocator.hpp"
#include <iostream>
#include <memory>
#include <string>
#include <vector>
namespace allocator_ {
// reference: C++ Primer(Fifth Edition) 12.2.2
int test_allocator_1()
{
std::allocator<std::string> alloc; // 可以分配string的allocator对象
int n{ 5 };
auto const p = alloc.allocate(n); // 分配n个未初始化的string
auto q = p; // q指向最后构造的元素之后的位置
std::cout << *p << std::endl; // 正确:使⽤string的输出运算符
//std::cout << *q << std::endl; // 灾难:q指向未构造的内存
std::cout << p[0] << std::endl;
std::cout << p[1] << std::endl;
std::cout << p[2] << std::endl;
while (q != p) {
alloc.destroy(--q); // 释放我们真正构造的string
}
alloc.deallocate(p, n);
return 0;
}
int test_allocator_2()
{
std::vector<int> vi{ 1, 2, 3, 4, 5 };
// 分配⽐vi中元素所占⽤空间⼤⼀倍的动态内存
std::allocator<int> alloc;
auto p = alloc.allocate(vi.size() * 2);
// 通过拷贝vi中的元素来构造从p开始的元素
/* 类似拷贝算法,uninitialized_copy接受三个迭代器参数。前两个表⽰输⼊序列,第三个表⽰
这些元素将要拷贝到的⽬的空间。传递给uninitialized_copy的⽬的位置迭代器必须指向未构造的内存。与copy不同,uninitialized_copy在给定⽬的位置构造元素。
类似copy,uninitialized_copy返回(递增后的)⽬的位置迭代器。因此,⼀次uninitialized_copy调⽤会返回⼀个指针,指向最后⼀个构造的元素之后的位置。
*/
auto q = std::uninitialized_copy(vi.begin(), vi.end(), p);
// 将剩余元素初始化为42
std::uninitialized_fill_n(q, vi.size(), 42);
return 0;
}
// reference: dernescpp/index.php/memory-management-with-std-allocator int test_allocator_3()
定义数组初始化
{
std::cout << std::endl;
std::allocator<int> intAlloc;
std::cout << "intAlloc.max_size(): " << intAlloc.max_size() << std::endl;
int* intArray = intAlloc.allocate(100);
std::cout << "intArray[4]: " << intArray[4] << std::endl;
intArray[4] = 2011;
std::cout << "intArray[4]: " << intArray[4] << std::endl;
intAlloc.deallocate(intArray, 100);
std::cout << std::endl;
std::allocator<double> doubleAlloc;
std::cout << "doubleAlloc.max_size(): " << doubleAlloc.max_size() << std::endl;
std::cout << std::endl;
std::allocator<std::string> stringAlloc;
std::cout << "stringAlloc.max_size(): " << stringAlloc.max_size() << std::endl;
std::string* myString = stringAlloc.allocate(3);
std::cout << myString[0] << " " << myString[1] << " " << myString[2] << std::endl;
stringAlloc.destroy(myString);
stringAlloc.destroy(myString + 1);
stringAlloc.destroy(myString + 2);
stringAlloc.deallocate(myString, 3);
std::cout << std::endl;
return 0;
}
//
// reference: en.cppreference/w/cpp/memory/allocator
int test_allocator_4()
{
std::allocator<int> a1;  // default allocator for ints
int* a = a1.allocate(1);  // space for one int
std::cout << a[0] << '\n';
a1.deallocate(a, 1);      // deallocate space for one int
// default allocator for strings
std::allocator<std::string> a2;
// same, but obtained by rebinding from the type of a1
decltype(a1)::rebind<std::string>::other a2_1;
// same, but obtained by rebinding from the type of a1 via allocator_traits
std::allocator_traits<decltype(a1)>::rebind_alloc<std::string> a2_2;
std::string* s = a2.allocate(2); // space for 2 strings
std::cout << s[0] << ' ' << s[1] << '\n';
a2.destroy(s);
a2.destroy(s + 1);
a2.deallocate(s, 2);
return 0;
}
} // namespace allocator_
更多详情
有默认的构造函数:
如果⼀个类有默认的构造函数,使⽤new动态实例化⼀个对象数组不是件难事,如下代码:class animal
{
public:
animal():num(0)
{}
~animal()
{}
private:
int num;
};
Animal *ani = new Animal[5];
delete[]ani;
然⽽ new Obj[n]的形式仅仅适⽤于不需传⼊实参的默认构造函数,否则编译器报错。
没有默认构造函数|初始化对象数组的同时指定参数
想要初始化对象数组的同时指定各个构造函数的参数,有以下⼏种解决途径:
静态数组
1.若初始化对象数组时已知其size,使⽤诸如 new Obj[n]{(),(),...()} 的形式,⼤括号内每个⼩括号对应每个对象的构造函数参数:
class Array1D
{
public:
Array1D(int len2)
:len2D(len2)
{
plist = new T[len2];
for (int i = 0; i < len2; i++)
plist[i] = static_cast<T>(0);
}
~Array1D()
{
if (nullptr != plist)
delete[] plist;
}
private:
T* plist;
int len2D;
};
pArray1D = new Array1D[2]{(1),(2)}
构造函数有多个参数时:
pArray1D = new Array1D[2]{{1,100},{2,199}}
动态数组
2.若初始化对象数组时未知其size,需要把分配内存和构建对象的动作分开。可借助C++11的allocator。先使⽤allocate分配内存并⽤指针记录这块空间;然后⽤construct⽅法对指针所指向内存进⾏对象构建;当然不再使⽤对象时⽤destory⽅法析构对象;注意,既然分配内存和构建对象动作已分
开,那么析构对象和释放内存也要配对,⽤deallocate释放内存:
class Array2D
{
public:
//class Array1D
class Array1D
{...};
//Array2D
Array2D(int len1, int len2)
:len1D(len1)
{
pArray1D = alloc.allocate(len1);
for (int i = 0; i < len1; i++) {
}
}
~Array2D()
{
for (int i = 0; i < len1D; i++) {
alloc.destroy(pArray1D + i);
}
alloc.deallocate(pArray1D, len1D);
}
private:
Array1D* pArray1D;

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。