Proper way to create unique_ptr that holds an allocated array

前端 未结 6 2025
天命终不由人
天命终不由人 2020-12-07 11:31

What is the proper way to create an unique_ptr that holds an array that is allocated on the free store? Visual studio 2013 supports this by default, but when I use gcc versi

6条回答
  •  不知归路
    2020-12-07 11:35

    Using the T[] specialisation:

    std::unique_ptr testData(new unsigned char[16000]());
    

    Note that, in an ideal world, you would not have to explicitly use new to instantiate a unique_ptr, avoiding a potential exception safety pitfall. To this end, C++14 provides you with the std::make_unique function template. See this excellent GOTW for more details. The syntax is:

    auto testData = std::make_unique(16000);
    

提交回复
热议问题