【发布时间】:2014-06-18 03:46:20
【问题描述】:
我有一个(看似)聪明的想法,即在 #include <memory> 之后立即在 stdafx.h 中使用 extern template class std::shared_ptr<SomeWidelyUsedClass>,以防止 std::shared_ptr<SomeWidelyUsedClass> 在数百个文件中被冗余实例化,我想我可以将 template class std::shared_ptr<SomeWidelyUsedClass> 放在单个 .cpp 以强制进行单个实例化并希望节省编译/链接时间。然而,对生成的 .cod 和 .obj 文件的检查表明,shared_ptr<SomeWidelyUsedClass> 代码无论如何都在到处创建。但是,如果我在自己的模板类中使用这种完全相同的技术,它就会按预期工作。 shared_ptr 有什么特别的地方排除了这种用途吗?也许<memory> 本身中的某些东西会强制编译器在它到达我的extern template 语句之前创建一个实例化(我很确定stdafx.h 中没有任何更高的东西使用shared_ptr)?
澄清一下:
// stdafx.h; included in every cpp in the project
#include <memory>
#include "SomeWidelyUsedClass.h" // no shared_ptr in here
// I expect this to prevent instantiation of std::shared_ptr<SomeWidelyUsedClass>
// in all compilation units that include this, except the one below.
extern template class std::shared_ptr<SomeWidelyUsedClass>;
然后:
// ExplicitTemplateInstantiations.cpp
#include "stdafx.h"
// I expect this to cause std::shared_ptr<SomeWidelyUsedClass>
// to be instantiated in this compilation unit
template class std::shared_ptr<SomeWidelyUsedClass>;
还有:
// SomeOtherFile.cpp
#include "stdafx.h"
#include "SomeWidelyUsedClass.h"
void foo()
{
// I expect that SomeOtherFile.obj will not include an instantiation of
// std::shared_ptr<SomeWidelyUsedClass> since it was declared extern in stdafx.h
std::shared_ptr<SomeWidelyUsedClass>(new SomeWidelyUsedClass());
}
【问题讨论】:
-
有一些代码将有助于理解和诊断问题。
-
不知道,这个问题看起来很合理。不过不知道答案。
-
@RSahu 用代码编辑
-
我记得你必须获得 VS2013 才能获得
extern template的支持,即使那样它也很不稳定
标签: c++ templates visual-c++ visual-studio-2012 explicit-specialization