Search code examples
c++c++buildervclunique-ptrtstringlist

unique_ptr<TStringList []> dsts(new TStringList[5]) fail


MyEnvironment:

C++ Builder XE4

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

Following didn't give any error:

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

On the other hand, following shows error:

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

The error is 'access violation at 0x000000000: read of address 0x0000000'.

For TStringList, can't I use array of unique_ptr<>?


Solution

  • It isn't a unique_ptr issue: your attempt fails because you are trying to create an array of actual TStringList object instances instead of an array of pointers to TStringList instances (for further details you can take a look at How to create an array of buttons on Borland C++ Builder and work with it? and Quality Central report #78902).

    E.g. You'll get an access violation even if you try:

    TStringList *sls(new TStringList[10]);
    

    (pointer to a dynamic array of size 10 and type TStringList).

    You have 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);
    

    Anyway, if the size is known at compile time, this is a better choice:

    boost::array<std::unique_ptr<TStringList>, 10> sls;
    

    (also take a look at Is there any use for unique_ptr with array?)