How do I declare an array of objects whose class has no default constructor?

后端 未结 13 1085
时光取名叫无心
时光取名叫无心 2020-11-30 06:25

If a class has only one constructor with one parameter, how to declare an array? I know that vector is recommended in this case. For example, if I have a class



        
13条回答
  •  抹茶落季
    2020-11-30 06:41

    sbi had the best answer for plain arrays, but didn't give an example. So...

    You should use placement new:

    char *place = new char [sizeof(Foo) * 10000];
    Foo *fooArray = reinterpret_cast(place);
    for (unsigned int i = 0; i < 10000; ++i) {
        new (fooArray + i) Foo(i); // Call non-default constructor
    }
    

    Keep in mind that when using placement new, you are responsible for calling the objects' destructors -- the compiler won't do it for you:

    // In some cleanup code somewhere ...
    for (unsigned int i = 0; i < 10000; ++i) {
        fooArray[i].~Foo();
    }
    
    // Don't forget to delete the "place"
    delete [] reinterpret_cast(fooArray);
    

    This is about the only time you ever see a legitimate explicit call to a destructor.

    NOTE: The first version of this had a subtle bug when deleting the "place". It's important to cast the "place" back to the same type that was newed. In other words, fooArray must be cast back to char * when deleting it. See the comments below for an explanation.

提交回复
热议问题