This is not a problem unique_ptr
: your attempt fails because you are trying to create an array of actual object instances TStringList
instead of an array of pointers to instances TStringList
(for more information, you can take a look at How to create an array of buttons in Borland C ++ Builder and work with it? And Quality Central report No. 78902 ).
eg. You will get an access violation even if you try:
TStringList *sls(new TStringList[10]);
(pointer to dynamic array of size 10
and type TStringList
).
You need to manage a pointer to a dynamic array of type TStringList *
. Using 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);
In any case, if the size is known at compile time, this is the best choice:
boost::array<std::unique_ptr<TStringList>, 10> sls;
(also take a look at Is there any use for unique_ptr with an array? )
source
to share