我曾经有一个(看似)聪明的想法,即在stdafx.h中包含#include 后立即使用extern template class std::shared_ptr,以防止std::shared_ptr在数百个文件中被重复实例化,我认为我可以将template class std::shared_ptr放在单个.cpp文件中,以强制进行单个实例化,并希望节省编译/链接时间。然而,对生成的.cod和.obj文件的检查表明,shared_ptr代码仍然在所有地方创建。但是,如果我对自己的模板类使用完全相同的技术,则按预期工作。shared_ptr有什么特殊之处,不允许这种用法吗?也许是在本身中有些东西强制编译器在达到我的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());
}
extern template
支持,即使这样也不是很稳定。 - Mgetz