C ++模板静态成员实例化 [英] C++ template static member instantiation

查看:127
本文介绍了C ++模板静态成员实例化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include <map>
#include <iostream>
template <typename T>
class A 
{
 static std::map<int, int> data;
public:
 A()
 {
  std::cout << data.size() << std::endl;
  data[3] = 4;
 }
};

template <typename T>
std::map<int, int> A<T>::data;

//std::map<int, int> A<char>::data;

A<char> a;

int main()
{
 return 0;
}

这有什么问题?在没有显式实例化的情况下,它在

What is wrong with this? Without explicit instantiation it breaks at

 data[3] = 4; 

处中断.显式实例化解决了该问题,但是程序在

Explicit instantiation solves the problem but the program breaks after

std::cout << data.size() << std::endl;

之后中断了,这意味着静态类模板成员data被实例化了.

what means that the static class template memeber data was instantiated.

推荐答案

您的代码中没有显式实例化.

There is no explicit instantiation in your code.

在其他静态数据成员中,没有实例化静态数据成员的初始化顺序.因此,您的代码实际上具有未定义的行为:根据编译器是首先初始化映射还是a,对映射的引用是否有效.

There is no order of initialization of instantiated static data members among other static data members. So your code has effectively undefined behavior: Depending on whether the compiler first initializes the map or a, the reference to the map is valid or not.

请参见 C ++静态成员初始化.

这篇关于C ++模板静态成员实例化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆