-3

I read that if I want to define array of elements from a type T , so class T must a default c'tor (It's correct, yes?).

But what about defining container (from the STL) of elements from type T?

HolyBlackCat
  • 78,603
  • 9
  • 131
  • 207
Software_t
  • 576
  • 1
  • 4
  • 13
  • You could try it and see if it works... – HolyBlackCat Jul 09 '18 at 21:00
  • @HolyBlackCat Yes I know, but I want explanation about that. – Software_t Jul 09 '18 at 21:01
  • @Software_t, each container and its member functions impose different constraints on `T`. This is not a good place to address all of them. – R Sahu Jul 09 '18 at 21:03
  • @R Sahu I don't believe any Standard Library containers require the values they store to be default constructible. –  Jul 09 '18 at 21:13
  • @NeilButterworth, DefaultConstructible is referenced in lots of places in the C++11 Standard. I, obviously, didn't do a thorough check of how many of those are related to containers (or specific member functions of containers). `map::operator[]` requires the `mapped_type` to be DefaultConstructible. I suspect there are other container member functions that require `T` to be DefaultConstructible but I don't have a comprehensive list. – R Sahu Jul 09 '18 at 21:46
  • @R Sahu Oh, yes, I forgot about map - my mistake. –  Jul 09 '18 at 21:50

1 Answers1

0

You don't need default constructors in both cases.

#include <iostream>
#include <vector>

struct A
{
    int x;
    A(int x) : x(x) {}
};

int main()
{
    A arr[3] {A(0), A(1), A(2)}; // An array

    std::vector<A> vec; // A std container
    vec.push_back(A(0));
    vec.push_back(A(1));
    vec.push_back(A(2));
}

Though, for some containers the lack of default constructor disables some operations, like operator[] of std::map and std::unordered_map.

HolyBlackCat
  • 78,603
  • 9
  • 131
  • 207
  • But you will need a copy c'tor, yes? – Software_t Jul 09 '18 at 21:05
  • 2
    @Software_t Open the description of your favorite container on https://en.cppreference.com/ ([here's the link for `std::vector`](https://en.cppreference.com/w/cpp/container/vector)), look for requirements for element types. – HolyBlackCat Jul 09 '18 at 21:08