Proper way to create unique_ptr that holds an allocated array

前端 未结 6 2030
天命终不由人
天命终不由人 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:36

    A most likely better way would be to use std::vector instead

    #include 
    #include 
    
    using namespace std;
    
    int main()
    {
        vector testData(0x12, 0); // replaces your memset
        // bla    
    }
    

    The advantage is that this is much less error-prone and gives you access to all kinds of features such as easy iteration, insertion, automatic reallocation when capacity has been reached.

    There is one caveat: if you are moving your data around a lot, a std::vector costs a little more because it keeps track of the size and capacity as well, rather than only the beginning of the data.

    Note: your memset doesn't do anything because you call it with a zero count argument.

提交回复
热议问题