Proper way to create unique_ptr that holds an allocated array

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

    Seems like a goofup, i will explain what i mean

    class Object {
    private :
        static int count;
    public :
        Object() {
            cout << "Object Initialized " << endl;
            count++;
        }
        ~Object() {
            cout << "Object destroyed " << endl;
        }
        int print()
        {
            cout << "Printing" << endl;
            return count;
        }
    };
    
    int Object::count = 0;
    
    int main(int argc,char** argv)
    {
        // This will create a pointer of Object
        unique_ptr up2 = make_unique();  
        up2->print();
        // This will create a pointer to array of Objects, The below two are same. 
        unique_ptr up1 = std::make_unique(30);
        Object obj[30];
        cout << up1.get()[8].print();
        cout << obj[8].print();
    
        // this will create a array of pointers to obj. 
            unique_ptr up= std::make_unique(30);
            up.get()[5] = new Object();
            unique_ptr mk = make_unique(*up.get()[5]);
            cout << up.get()[5]->print();
    
            unique_ptr[]> up3 =  std::make_unique[]>(20);
            up3.get()[5] = make_unique();
    
        return 0;
    }
    
    
    

    Objective of the post is that there are hidden small subtle things you need to understand. Creating array of objects is same as object array of unique_ptr. It will make difference only when you pass it in the argument. Creating array of object pointers of unique_ptr is also not very useful. So only below two you need to use in most scenarios.

    unique_ptr obj;
    //and 
    unique_ptr[]>= make_unique[]>(20);
    
        

    提交回复
    热议问题