我试图弄清楚clang如何确定C ++模板静态成员变量需要实例化,并且我看到一些令我困惑的行为。
给出以下代码:
#include <stdio.h> #include <typeinfo> int report(const char *name) { printf("Reporting class: %s\n", name); return 0; } template<typename ReportedClass> class reported_class { public: reported_class() { _reported_instances++; } private: static int _reported_instances; }; template<typename ReportedClass> int reported_class<ReportedClass>::_reported_instances = report(typeid(ReportedClass).name()); class foo : reported_class<foo> { public: int baz() { return 0; } }; class bar : reported_class<bar> { public: bar() { } int baz() { return 0; } }; int main(int argc, char **argv) { return 0; }当我运行它时,我看到以下内容:
$ c++ -v Apple LLVM version 5.0 (clang-500.0.68) (based on LLVM 3.3svn) Target: x86_64-apple-darwin13.1.0 Thread model: posix $ c++ test.cpp $ ./a.out Reporting class: 3bar $为什么report_class的静态实例化,而不是foo的静态? 唯一的区别似乎是构造函数的存在,但我希望在任何一种情况下都会调用reported_class构造函数(因此在构造函数中使用时会强制执行静态实例化)。 标准中是否有这样的理由我不知道,这是否可以依赖?
gcc-4.7.3显示相同的行为,所以我认为这是我误解的事情。
I’m trying to puzzle out how clang determines what C++ template static member variables require instantiation, and I’m seeing some behavior that has me confused.
Given the following code:
#include <stdio.h> #include <typeinfo> int report(const char *name) { printf("Reporting class: %s\n", name); return 0; } template<typename ReportedClass> class reported_class { public: reported_class() { _reported_instances++; } private: static int _reported_instances; }; template<typename ReportedClass> int reported_class<ReportedClass>::_reported_instances = report(typeid(ReportedClass).name()); class foo : reported_class<foo> { public: int baz() { return 0; } }; class bar : reported_class<bar> { public: bar() { } int baz() { return 0; } }; int main(int argc, char **argv) { return 0; }When I run it, I see the following:
$ c++ -v Apple LLVM version 5.0 (clang-500.0.68) (based on LLVM 3.3svn) Target: x86_64-apple-darwin13.1.0 Thread model: posix $ c++ test.cpp $ ./a.out Reporting class: 3bar $Why is the static for reported_class being instantiated, but not the one for foo? The only difference appears to be the presence of a constructor, but I’d expect the reported_class constructor to be called in either case (therefore forcing static instantiation due to use in the constructor). Is there a reason for this in the standard that I’m not aware of, and is this something that can be relied upon?
gcc-4.7.3 displays the same behavior, so I assume that this is something that I"m misunderstanding.
最满意答案
显然在未显示的main函数中,您没有实例化任何一个类。
然后,编译器没有理由为类foo生成默认构造函数。
没有它,就没有实例化reported_class<foo>代码。
Apparently in the not shown main function you're not instantiating either class.
Then there's no reason for the compiler to generate a default constructor for class foo.
And without that, there's no code that instantiates reported_class<foo>.
更多推荐
发布评论