特性
- 管理動態陣列(
new T[n]),析構時自動 delete[]。
- 不可複製(non-copyable),可移動(C++11 移動語意)。
- 提供
operator[]、get()、reset()、swap()。
- 輕量,無參考計數開銷。
標頭
#include <boost/scoped_array.hpp>
程式碼
/* test.cpp
* Created on: 2014.04.18
* Author: Spike
*/
#include <iostream>
#include <boost/scoped_array.hpp>
using namespace std;
int main() {
const int n = 3;
boost::scoped_array<int> pData(new int[n * n]);
int temp[9] = {0,1,2,3,4,5,6,7,8};
pData.reset(temp); // 重置指向靜態陣列(不會 delete[] temp)
for (size_t i = 0; i < n * n; ++i)
cout << "pData[" << i << "] = " << pData[i] << endl;
return 0;
}
輸出
pData[0] = 0
pData[1] = 1
...
pData[8] = 8
注意
reset(ptr) 若 ptr 非 new[] 分配,析構時會錯誤 delete[] 該位址。範例中 temp 為靜態陣列僅供演示,實際使用請確保所有權轉移正確。
- 現代 C++ (C++11+) 建議使用
std::unique_ptr<T[]> 替代,標準庫無相依。