std::vector works with classes that are not default constructible?

前端 未结 4 811
醉话见心
醉话见心 2021-02-14 01:36

I\'ve read in several places that std::vector requires it\'s template argument to be default constructible. Today I just tried it with one of my classes that has a delete<

4条回答
  •  耶瑟儿~
    2021-02-14 02:14

    std::vector does not unconditionally require its elements type to be default-constructible.

    The original specification of std::vector (C++98, C++03) never even attempts to default-construct its elements internally. All new elements are always copy-constructed from an object supplied "from outside" (by the calling code) as an argument. This means that every time you need default-constructed elements in your vector, it is your side of the code (the caller) that has to default-construct it and supply it to std::vector as the "original" element to be copied.

    For example, when you do something like this in C++98

    std::vector v(42);
    v.resize(64);
    

    it actually expands into

    std::vector v(42, some_type(), allocator_type());
    v.resize(64, some_type());
    

    through the default argument mechanism. In other words, the default-constructed "original" element is supplied to vector's constructor by the calling code, not created internally by the vector.

    C++11 changed that and now std::vector has methods that perform default construction of its elements internally. This still does not unconditionally require vector elements to be default-constructible. It just means that you need default-constructible elements to use those specific std::vector's methods.

提交回复
热议问题