隐式构造函数/继承构造函数和用户定义构造函数的不同行为

时间:2017-06-03 07:34:07

标签: c++

我有一段代码在启动应用程序时自动为类运行一个函数:

template<class T> struct RegClass;

template <typename T>
struct AutoRegister {
  AutoRegister() { (void)&ourRegisterer; }
private:
  static RegClass<T> ourRegisterer;
};

template <typename T>
RegClass<T> AutoRegister<T>::ourRegisterer;

template<class T>
struct RegClass {
  RegClass() {
    printf("registering\n");
  }
};

要将它用于课程,我只需继承AutoRegister<T>

struct Foo : AutoRegister<Foo>{
  Foo() {}
};

在此示例中,即使没有设置Foo类型的对象,应用程序也会打印出“注册”。 http://coliru.stacked-crooked.com/a/fc1678b1a18e8971

但是,似乎需要定义Foo的构造函数来观察此行为。隐式构造函数或继承基类的构造函数是不够的:http://coliru.stacked-crooked.com/a/a54c53afe2724cdf

感谢您关联What are rules for a class static variable initialization?

我看了一下继承构造函数,并且它们具有与隐式构造函数相同的“定义时使用”规则,这也解释了该部分

0 个答案:

没有答案
相关问题