【问题标题】:unique_ptr<TStringList []> dsts(new TStringList[5]) failunique_ptr<TStringList []> dsts(new TStringList[5]) 失败
【发布时间】:2015-08-17 06:05:03
【问题描述】:

我的环境:

C++ Builder XE4

我正在尝试通过 unique_ptr&lt;&gt; 使用 TStringList 的数组。

以下没有给出任何错误:

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

另一方面,以下显示错误:

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

错误是“0x000000000 处的访问冲突:读取地址 0x0000000”。

对于TStringList,我不能使用unique_ptr&lt;&gt;的数组吗?

【问题讨论】:

    标签: c++ c++builder vcl unique-ptr tstringlist


    【解决方案1】:

    这不是unique_ptr 问题:您的尝试失败了,因为您试图创建一个实际的TStringList 对象实例数组,而不是一个指向TStringList 实例的指针数组(有关更多详细信息,您可以采取看看How to create an array of buttons on Borland C++ Builder and work with it?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?

    【讨论】:

    • new T[] 确实在堆上创建对象。
    • @MattMcNabb 你说得对,答案不准确(现已修复)。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2014-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-21
    • 1970-01-01
    • 2023-03-13
    • 1970-01-01
    相关资源
    最近更新 更多