gpt4 book ai didi

c++ - 模板类的静态变量初始化,c++

转载 作者:行者123 更新时间:2023-11-30 03:53:53 33 4
gpt4 key购买 nike

考虑以下代码:

//header.h
template<class T>
class A
{
static int x;
};

template<class T>
int A<T>::x = 0;

//source1.cpp
#include "header.h"
void f(){} // dummy function


//main.cpp
#include "header.h"
int main(){}

在这种情况下,代码可以完美无误地编译,但是如果我从类中删除模板限定符

class A
{
static int x;
};

int A::x = 0;
  1. 在这种情况下,编译器因 x 的多重定义而出错。谁能解释这种行为?
  2. 以及何时初始化/实例化模板类的静态变量?

最佳答案

编译器将自行删除重复的模板实例化。如果您将模板类变成常规类,那么您有责任确保只存在一个静态变量定义(否则将出现链接器错误)。还要记住,静态数据成员不会在不同类型的模板实例化之间共享。使用 c++11,您可以使用外部模板自行控制实例化:using extern template (C++11) .

关于静态成员的实例化点:

14.6.4.1 Point of instantiation [temp.point] 1 For a function template specialization, a member function template specialization, or a specialization for a member function or static data member of a class template, if the specialization is implicitly instantiated because it is referenced from within another template specialization and the context from which it is referenced depends on a template parameter, the point of instantiation of the specialization is the point of instantiation of the enclosing specialization. Otherwise, the point of instantiation for such a specialization immediately follows the namespace scope declaration or definition that refers to the specialization.

所以实例化点应该是 ie。如果您是第一次在 main() 中使用您的类型,则紧接在 main() 之后。

关于c++ - 模板类的静态变量初始化,c++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29889604/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com