While explicitly instantiating vector, what is the someType default constructor used for?

后端 未结 3 681
滥情空心
滥情空心 2021-02-10 08:09

It\'s an exercise from C++ Primer 5th Edition:

Exercise 16.26: Assuming NoDefault is a class that does not have a default constructor, can we e

3条回答
  •  一向
    一向 (楼主)
    2021-02-10 08:54

    As already said, the default constructor is required to create vector of objects. However, if one were to create a classic dynamic array (contiguous area of memory), it would be possible to address the lack of a default constructor using the placement new syntax:

    #include 
    
    struct Foo {
        explicit Foo(int a): a(a) {}
        int a;
    };
    
    int main() {
        void* mem = operator new[](10*sizeof(Foo));
        Foo* ptr = static_cast(mem);
        for (int i = 0; i < 10; ++i ) {
            new(&ptr[i])Foo(i);
            std::cout << ptr[i].a;
        }
        return 0;
    }
    

提交回复
热议问题