MyEnvironment:
C++ Builder XE4
我正在尝试使用TStringList
使用unique_ptr<>
数组。
以下没有给出任何错误:
unique_ptr<int []> vals(new int [10]);
另一方面,以下显示错误:
unique_ptr<TStringList []> sls(new TStringList [10]);
错误是'0x000000000处的访问冲突:读取地址0x0000000'。
对于TStringList
,我不能使用unique_ptr<>
数组吗?
答案 0 :(得分:3)
这不是unique_ptr
问题:您尝试失败,因为您尝试创建一个实际TStringList
对象实例的数组,而不是指向TStringList
个实例的指针数组(用于更多详细信息,您可以查看How to create an array of buttons on Borland C++ Builder and work with it?和Quality Central report #78902)。
E.g。即使您尝试,也会遇到访问冲突:
TStringList *sls(new TStringList[10]);
(指向大小为10
且类型为TStringList
的动态数组的指针)。
您必须管理指向TStringList *
类型的动态数组的指针。使用std::unique_ptr
:
std::unique_ptr< std::unique_ptr<TStringList> [] > sls(
new std::unique_ptr<TStringList>[10]);
sls[0].reset(new TStringList);
sls[1].reset(new TStringList);
sls[0]->Add("Test 00");
sls[0]->Add("Test 01");
sls[1]->Add("Test 10");
sls[1]->Add("Test 11");
ShowMessage(sls[0]->Text);
ShowMessage(sls[1]->Text);
无论如何,如果在编译时知道大小,这是一个更好的选择:
boost::array<std::unique_ptr<TStringList>, 10> sls;