何时在C ++中调用模板类的静态成员的构造函数?

编程入门 行业动态 更新时间:2024-10-27 09:33:28
本文介绍了何时在C ++中调用模板类的静态成员的构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

关于何时调用普通类的静态成员的构造函数,有很多信息。但是,我看到一些有关模板类的奇怪行为。

There is plenty of information on when constructors of static members of ordinary classes are called. However, I am seeing some strange behavior with regard to template classes.

以下程序的输出应该是什么? (请注意,我使用printf可以避免任何带有std :: cout的静态初始化订单惨败的并发症。)

What should the output of the following program be? (Note I use printf to avoid any static initialization order fiasco complications with std::cout.)

#include <iostream> class B { public: B(const std::string &s) { printf("Hello I am B from %s\n", s.c_str()); } }; template<typename T> class Atempl { public: static B b_; }; class A { public: static B b_; }; template<typename T> B Atempl<T>::b_("Atempl"); B A::b_("A"); class C : public Atempl<int> { }; int main(int argc, const char *argv[]) { return 0; }

我认为输出应该是:

Hello I am B from A Hello I am B from Atempl

但是在FreeBSD 7.3上使用g ++ 4.3时,我得到:

But with g++ 4.3 on FreeBSD 7.3 I get:

Hello I am B from A

如果我添加行

template class Atempl<int>;

一切都很好,我得到了预期的输出。问题是,为什么不将类C的声明计为模板 Atempl 的实例并导致B的构造函数被调用?这是标准的一部分还是g ++ 4.3中的错误?

all is well and I get the expected output. The question is, why doesn't the declaration of class C count as an instantiation of the template Atempl and cause B's constructor to be called? Is this part of the standard or a bug in g++ 4.3?

推荐答案

在类模板中,执行隐式实例化时,成员按需实例化。由于代码不使用静态成员,因此它甚至不会在整个应用程序中实例化。

In a class template, when performing implicit instantiation, the members are instantiated on demand. Since the code does not use the static member, it is not even instantiated in the whole application.

进行显式实例化时,整个类及其所有成员被实例化,其中包括静态成员变量,然后将其初始化,您将获得预期的结果。

When you do an explicit intantiation, the whole class and all of its members are instantiated, and that includes the static member variable, which is then initialized and you get your expected result.

没有显式实例化,您可以执行 B * p =& Atempl< int> :: b _; (或对静态成员的任何其他使用)来触发实例化。

Without the explicit instantiation you could do something like B* p = &Atempl<int>::b_; (or any other use of the static member) to trigger the instantiation.

更多推荐

何时在C ++中调用模板类的静态成员的构造函数?

本文发布于:2023-11-22 07:07:39,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1616439.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:静态   函数   模板   成员

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!