析构函数``virtual时,几乎没有区别,否则: default时:认为是 trivial {}时: 认为是 user-defined

区别

如下为trivial class的两种实现:

  1. struct Trivial
  2. {
  3. int foo;
  4. };
  5. struct Trivial_Default
  6. {
  7. int foo;
  8. Trivial_Default() = default;
  9. };

如下为non-trivial的实现:

  1. struct Non_Trivial
  2. {
  3. int foo;
  4. Non_Trivial(){}
  5. };

什么是trivial

The C++ Standard n3337 § 8.5/7 says

To value-initialize an object of type T means: — if T is a (possibly cv-qualified) class type (Clause 9) with a user-provided constructor (12.1), then the default constructor for T is called (and the initialization is ill-formed if T has no accessible default constructor); — if T is a (possibly cv-qualified) non-union class type without a user-provided constructor, then the object is zero-initialized and, if T’s implicitly-declared default constructor is non-trivial, that constructor is called. — if T is an array type, then each element is value-initialized; — otherwise, the object is zero-initialized.

举例如下

  1. #include <iostream>
  2. class A {
  3. public:
  4. A(){}
  5. int i;
  6. int j;
  7. };
  8. class B {
  9. public:
  10. B() = default;
  11. int i;
  12. int j;
  13. };
  14. int main()
  15. {
  16. for( int i = 0; i < 100; ++i) {
  17. A* pa = new A();
  18. B* pb = new B();
  19. std::cout << <<pa->i << "," << pa->j << std::endl;
  20. std::cout << pb->i << "," << pb->j << std::endl;
  21. delete pa;
  22. delete pb;
  23. }
  24. return 0;
  25. }

结果如下:
image.png