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

后端 未结 13 1124
时光取名叫无心
时光取名叫无心 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:52

    Another option might be to use an array of boost::optional:

    boost::optional foos[10]; // No construction takes place
                                   // (similar to vector::reserve)
    
    foos[i] = Foo(3); // Actual construction
    

    One caveat is that you'll have to access the elements with pointer syntax:

    bar(*foos[2]); // "bar" is a function taking a "Foo"
    
    std::cout << foos[3]->baz(); // "baz" is a member of "Foo"
    

    You must also be careful not to access an unitialized element.

    Another caveat is that this not a true replacement for an array of Foo, as you won't be able to pass it to a function that expects the latter.

提交回复
热议问题