Aggregates
Definition
- array type
- class type that has
- no private or protected members
- no user-provided constructors (explicitly defaulted or deleted constructors are allowed)
- no base classes
- no virtual member functions
- no brace-or-equal initializers for non-static members
정리하면 aggregate class는
- constructor를 직접 만들면 안된다.
- member는 aggregate이 아니어도 된다.
- non-static member는 public이어야 한다.
- static member나 function은 public이든 private이든 상관 없다.
- 상속하면 안되고 virtual function도 있으면 안된다.
- non-static member에 brace-or-equal initializer가 있으면 안된다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
class Aggregate { public: NotAggregate member; // it doesn't matter whether a member is an aggregate or not. Aggregate& operator=(Aggregate const& rhs) { /**/ } // user-provided assignment operator ok. ~Aggregate() {} // user-provided destructor ok. private: void f(); // private/protected function ok. static int i; // private/protected static member ok. }; class NotAggregate : public Base // no base classes. { public: NotAggregate(){} // no user-provided constructors. virtual void f(); // no virtual functions. private: int x; // no private/protected non-static members. }; |
What’s special
Aggregate은 {}로 initialize 할 수 있다. Memeber는 array에 들어 있는 순서 또는 class definition에 나오는 순서대로 해당하는 initializer list의 element를 통해 copy-initialize 된다. (copy elision 덕에 꼭 copy/move constructor가 불리지는 않는다.) initializer list에 element가 부족하면 남는 멤버는 value-initialize 되며, element가 넘치면 compile error이다.
1 2 |
T t[3] = {T(1), T(4)}; unsigned char b[5]{"abc"}; |
Aggregate은 Aggregate initialization이 가능해야한다는 관점에서 보면 정의를 이해하는데 도움이 되는 것 같다. Aggregate initialiation은 member를 각각 따로 initialize하는 것이라고 볼 수 있다. 그런데 user-provided constructor가 있으면 그 안에서 다른 동작을 더 할 수도 있기 때문에 aggregate initialization을 통해서 제대로 초기화가 됐다고 할 수 없다. (C++11에서는 aggregate이 아닌 것에 {}를 쓰면 std::initializer_list를 받는 생성자를 부른다.) 또, virtual 함수가 있으면 vptr 초기화가 문제가 된다. static member나 function은 각 instance가 아니라 class 전체에 속한 것이기 때문에 aggregate에 대한 제약이 없을 것이다. brace-or-equal initializer 가 있으면 사실상 user-provided constructor가 있는 것과 마찬가지이다. member가 private이어야 하는 이유는 순서가 애매해서일 것 같은데 잘 모르겠다.
PODs
Definition
C++03
- scalar type
- class type that is
- an aggregate type
- has no non-static members that are non-POD
- has no members of reference type
- has no user-defined copy constructor
- has no user-defined destructor
C++11
- scalar type
- class type that is
- trivial type
- standard layout type
다음 기회에 계속..