目錄
三、上面的只適合靜態數組,動態數組用C++11的allocator
即看即用
一、賦值初始化
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 var create...." << endl;
}
Acct( double init_balance ,double init_cc ) {
balance = init_balance;
cc = init_cc;
cout << "with var create..." << endl;
}
~Acct(){
cout << "delete..." << 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 C++ allocator類學習理解 - SimonKly - 博客園
請看一下代碼關於使用如何實現無默認構造函數,動態實例化對象數組的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()申請指定大小空間
3.construct()構建對象,其參數為可變參數,所以可以選擇匹配的構造函數
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)...);
*/
alloc.construct(a, 1);
alloc.construct(a + 1);
alloc.construct(a + 2, 3);
alloc.construct(a + 3);
alloc.construct(a + 4, 5);
//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);
cin.get();
return 0;
}
如果構造函數是多個參數,則可以這樣:
//3.
alloc.construct(a, Animal(50,"dog"));
alloc.construct(a + 1,Animal(30,"cat"));
alloc.construct(a + 2,Animal(100,"goal"));
alloc.construct(a + 3,Animal(65,"cow"));
alloc.construct(a + 4,Animal(5,"bird"));
C++中若類中沒有默認構造函數,如何使用對象數組 - SimonKly - 博客園
#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指向最后構造的元素之后的位置
alloc.construct(q++); // *q為空字符串
alloc.construct(q++, 10, 'c'); // *q為cccccccccc
alloc.construct(q++, "hi"); // *q為hi
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: http://www.modernescpp.com/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);
stringAlloc.construct(myString, "Hello");
stringAlloc.construct(myString + 1, "World");
stringAlloc.construct(myString + 2, "!");
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: http://en.cppreference.com/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
a1.construct(a, 7); // construct the 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
a2.construct(s, "foo");
a2.construct(s + 1, "bar");
std::cout << s[0] << ' ' << s[1] << '\n';
a2.destroy(s);
a2.destroy(s + 1);
a2.deallocate(s, 2);
return 0;
}
} // namespace allocator_
C++中std::allocator的使用_網絡資源是無限的-CSDN博客_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++) {
alloc.construct(pArray1D + i, len2);
}
}
~Array2D()
{
for (int i = 0; i < len1D; i++) {
alloc.destroy(pArray1D + i);
}
alloc.deallocate(pArray1D, len1D);
}
private:
Array1D* pArray1D;
int len1D;
allocator<Array1D> alloc;
};
3.使用operator new和placement new,與allocator原理類似,分四步走:
class animal
{
public:
animal():num(0)
{}
animal(int _num):num(_num)
{}
~animal()
{}
void show() {
cout << num << endl;
}
void* operator new(size_t size, void* p)
{
return p;
}
private:
int num;
};
int main(int argc, char* argv[])
{
{
// operator new
void* p = operator new(5 * sizeof(animal));
animal* a = static_cast<animal*>(p);
// placement new, constructor
for (int i = 0; i < 4; i++)
{
new(a + i) animal(i);
}
new(a + 4) animal;
// use
for (int i = 0; i < 5; i++) {
(a + i)->show();
}
// destructor
for (int i = 0; i < 5; i++) {
(a + i)->~animal();
}
// delete
delete[] p;
}
return 0;
}
參考:https://www.cnblogs.com/SimonKly/p/7819147.html
原文鏈接:https://blog.csdn.net/brahmsjiang/article/details/88347005
//#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,string _name) : num(_num),name(_name)
{
cout << "Animal constructor param" << endl;
}
~Animal()
{
cout << "Animal destructor" << endl;
}
void show()
{
cout <<"num:"<<this->num << endl;
cout <<"name:"<< this->name << endl;
}
private:
int num;
string name;
};
/*
由於allocator將內存空間的分配和對象的構建分離
故使用allocator分為以下幾步:
1.allocator與類綁定,因為allocator是一個泛型類
2.allocate()申請指定大小空間
3.construct()構建對象,其參數為可變參數,所以可以選擇匹配的構造函數
4.使用,與其它指針使用無異
5.destroy()析構對象,此時空間還是可以使用
6.deallocate()回收空間
*/
int main()
{
allocator<Animal> alloc; //1.
Animal *a = alloc.allocate(5); //2.
//3.
alloc.construct(a, Animal(50,"dog"));
alloc.construct(a + 1,Animal(30,"cat"));
alloc.construct(a + 2,Animal(100,"goal"));
alloc.construct(a + 3,Animal(65,"cow"));
alloc.construct(a + 4,Animal(5,"bird"));
//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);
cin.get();
return 0;
}