Dynamically allocating an array of objects

前端 未结 7 1718
挽巷
挽巷 2020-11-22 13:05

I have a class that contains a dynamically allocated array, say

class A
{
    int* myArray;
    A()
    {
        myArray = 0;
    }
    A(int size)
    {
           


        
7条回答
  •  旧巷少年郎
    2020-11-22 13:25

    The constructor of your A object allocates another object dynamically and stores a pointer to that dynamically allocated object in a raw pointer.

    For that scenario, you must define your own copy constructor , assignment operator and destructor. The compiler generated ones will not work correctly. (This is a corollary to the "Law of the Big Three": A class with any of destructor, assignment operator, copy constructor generally needs all 3).

    You have defined your own destructor (and you mentioned creating a copy constructor), but you need to define both of the other 2 of the big three.

    An alternative is to store the pointer to your dynamically allocated int[] in some other object that will take care of these things for you. Something like a vector (as you mentioned) or a boost::shared_array<>.

    To boil this down - to take advantage of RAII to the full extent, you should avoid dealing with raw pointers to the extent possible.

    And since you asked for other style critiques, a minor one is that when you are deleting raw pointers you do not need to check for 0 before calling delete - delete handles that case by doing nothing so you don't have to clutter you code with the checks.

提交回复
热议问题