0

In the following sample code, C++ allows container of self class. But if a single object is created it's not allowed. I understand that class can have pointer to self type or static member object.

But how is container of self (not self pointer) is allowed? How is compiler able to get 'complete definition' for vector members?

#include <iostream>
#include <vector>

class Test {
    std::vector<Test> list; //but this works
    static Test t3; // this is allowed too
    // Test t2; // definition of 'class Test' is not complete

public:
    Test() {
        std::cout << "Test()" <<  std::endl;
        std::cout << list.size() <<  std::endl;
    }

};

int main() {
    Test t;
    return 0;
}
bladeWalker
  • 978
  • 1
  • 13
  • 30
  • 3
    Ask yourself: If a `Test` contains a `Test`, when would you ever stop constructing `Test`'s? – NathanOliver Jun 05 '19 at 19:12
  • 1
    Question is not "why self is not allowed". The question is "why container of self is allowed?". – bladeWalker Jun 05 '19 at 19:16
  • The vector could be empty at first, so there wouldn't be a recursive construction. Adding an element to the vector would then again create a vector, but that one would be empty again at the beginning... – Aconcagua Jun 05 '19 at 19:17
  • The answer to the question is essentially equivalent to "why a pointer of type `T` is allowed inside `T`?". Try to construct an `std::array` inside the `T` class. – Fureeish Jun 05 '19 at 19:19
  • I don't agree on the duplicate. The duplicates obviously seems to be clear to OP, but she/he's wondering about the difference with containers! – Aconcagua Jun 05 '19 at 19:19
  • @Aconcagua agree. Voted to reopen. – Fureeish Jun 05 '19 at 19:19
  • 3
    Possible duplicate of https://stackoverflow.com/questions/41913578/how-can-i-declare-a-member-vector-of-the-same-class – πάντα ῥεῖ Jun 05 '19 at 19:21
  • @πάνταῥεῖ That seems to be the correct dupe. – Nikos C. Jun 05 '19 at 19:23
  • TLDR of the duplicate is that `std::vector` of incomplete type has been made explicitly legal in C++17 with the right allocator and the default allocator allows it. – François Andrieux Jun 05 '19 at 19:24
  • 1
    @NikosC. I was overruled before having the chance to add it to the dupe links :-P – πάντα ῥεῖ Jun 05 '19 at 19:25
  • Could be worse. You could have been under-ruled. Remember "Measure once, cut twice. Measure twice, cut once." And I think that's my moment of peak absurdity for today. It's all downhill from here. – user4581301 Jun 05 '19 at 19:28

0 Answers0