Unique_ptr <TStringList []> dsts (new TStringList [5]) does not work

MyEnvironment:

C++ Builder XE4

      

I am trying to use a TStringList array using unique_ptr <>.

There were no problems:

unique_ptr<int []> vals(new int [10]);

      

On the other hand, the following shows an error:

unique_ptr<TStringList []> sls(new TStringList [10]);

      

Error: "Access violation at 0x000000000: reading address 0x0000000".

Can't use unique_ptr <> array for TStringList?

+3


source to share


1 answer


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? )

+3


source







All Articles