unique_ptr<TStringList []> dsts(new TStringList[5]) 失败
unique_ptr<TStringList []> dsts(new TStringList[5]) fail
我的环境:
C++ Builder XE4
我正在尝试使用 unique_ptr<>
的 TStringList
数组。
以下没有给出任何错误:
unique_ptr<int []> vals(new int [10]);
另一方面,以下显示错误:
unique_ptr<TStringList []> sls(new TStringList [10]);
错误是'access violation at 0x000000000: read of address 0x0000000'。
对于 TStringList
,我不能使用 unique_ptr<>
的数组吗?
这不是 unique_ptr
问题:您的尝试失败是因为您正在尝试创建一个实际的 TStringList
对象实例数组,而不是指向 TStringList
个实例的指针数组(有关详细信息,您可以查看 How to create an array of buttons on Borland C++ Builder and work with it? and Quality Central report #78902)。
例如即使您尝试,您也会遇到访问冲突:
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;
(也看看Is there any use for unique_ptr with array?)
我的环境:
C++ Builder XE4
我正在尝试使用 unique_ptr<>
的 TStringList
数组。
以下没有给出任何错误:
unique_ptr<int []> vals(new int [10]);
另一方面,以下显示错误:
unique_ptr<TStringList []> sls(new TStringList [10]);
错误是'access violation at 0x000000000: read of address 0x0000000'。
对于 TStringList
,我不能使用 unique_ptr<>
的数组吗?
这不是 unique_ptr
问题:您的尝试失败是因为您正在尝试创建一个实际的 TStringList
对象实例数组,而不是指向 TStringList
个实例的指针数组(有关详细信息,您可以查看 How to create an array of buttons on Borland C++ Builder and work with it? and Quality Central report #78902)。
例如即使您尝试,您也会遇到访问冲突:
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;
(也看看Is there any use for unique_ptr with array?)