开发者

Duplicate c++ template instantiations

Is it possible for the compiler to duplicate instantiations of a same template across several translation units?

For instance, if you have a.cpp which use a开发者_运维百科 std:vector<int> inside a function, and same thing for b.cpp, is there a risk of having two times std::vector<int> in the final binary?


As sharptooth says, the final binary will only contain one instantiation. But the templates will still be instantiated everytime they are encountered in a compilation unit. If you want some compilation speed, in C++0x we get the extern templates. It works like normal extern variables, in that it has to be specified in at least one compilation unit, but the compiler wont instantiate the template in this unit. See here and this draft (14.7.2 [temp.explicit]) for more infos.


This can happen while the project is being compiled, so different .obj files will have copies of the same instantiation. When the binary is linked the linker will eliminate all redundant copies of an instantiation, so the end binary will have only one copy.


It is possible, but only if you explicitly instantiate them, but then you will get a linker errors :

// header.hpp
template< typename T >
class A
{
};

// source1.cpp
template class A< int >;

// source2.cpp
template class A< int >;

If you are not explicitly instantiating templates, then any decent linker will easily eliminate copies.


I think that the compiler uses the same mechanism as with member functions of ordinary classes. It can make them inline and I presume that it leaves information around that the linker uses to sort it out for the final binary.

The only difference is that the compiler 'writes' the definitions - that is the 'instantiation' of a template - but it manages to make exactly the same instantiation whilst compiling either of a.cpp or b.cpp

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜