gpt4 book ai didi

c++ - 静态实例的未定义​​引用

转载 作者:太空宇宙 更新时间:2023-11-04 13:35:41 24 4
gpt4 key购买 nike

我目前正在将一些代码从 Visual Studio 移植到 Mingw GCC。当我尝试使用静态变量时似乎出现了问题。这段代码在 Visual Studio 中运行良好,所以我不确定这里可能有什么问题。我已经粘贴了代码的概要。如果这还不够,我可以添加更多。

Header file: .h
namespace LG_Wrapper
{
template <LG_Thread Thread>
class EffectApplication : public ktApplication
{
public:
static EffectApplication<Thread>& GetInstance();
protected:
.....
.....
static boost::recursive_mutex mResource;
}
}

DECLARE_LEGACY_TYPES(EffectApplication);


Source File: .cpp
namespace LG_Wrapper
{

template<>
boost::recursive_mutex EffectApplication<LG_Thread_NAME>::mResource; //LG_Thread_NAME type discussed below

template <LG_Thread Thread>
EffectApplication<Thread>& EffectApplication<Thread>::GetInstance()
{
boost::recursive_mutex::scoped_lock mutex( mResource ); //Error with mResource

static EffectApplication<Thread> instance;
return instance;
}
....
}

现在我不确定 LG_Thread_NAME 类型。通过代码后,我注意到我在项目设置中定义了以下内容

LG_THREAD_NAME=GAME

这个定义在代码的其他地方与这个宏一起发挥作用

#define DECLARE_LEGACY_TYPES(...)

我在访问 mResource 时遇到问题如果我注释掉该语句,代码构建正常

boost::recursive_mutex::scoped_lock mutex( mResource );

关于为什么我可能会在上面的代码中遇到以下错误有什么建议吗?

(.text$_ZN10KT_Wrapper17EffectApplicationILNS_9LT_ThreadE0EE11GetInstanceEv[_ZN10LT_Wrapper17EffectApplicationILNS_9LT_ThreadE0EE11GetInstanceEv]+0x11): undefined reference to `LT_Wrapper::EffectApplication<(LT_Wrapper::LT_Thread)0>::mResource'

更新:我确定变量 mResource 有问题,因为在静态方法中。如果我这样做,它会构建得很好

  boost::recursive_mutex l;
boost::recursive_mutex::scoped_lock mutex( l );

重复问题:我不确定这个问题如何与所提供的链接重复。在提供的所有链接中,ops 尚未初始化其静态变量。在这里,我在类外初始化了我的静态变量。

最佳答案

初始化

template<>
boost::recursive_mutex EffectApplication<LG_Thread_NAME>::mResource;

仍然不正确,因为您初始化 mResource 并非针对所有模板参数,而是仅针对 LG_Thread_NAME 的专门化。所以我想当您尝试使用其他模板参数访问它时会出错。

正确的做法是这样的

template<LG_Thread Thread>
boost::recursive_mutex EffectApplication<Thread>::mResource;

我也不确定我的答案,因为错误说问题出在 LT_Wrapper 类和模板参数 (LT_Wrapper::LT_Thread)0 看起来很奇怪我。

关于c++ - 静态实例的未定义​​引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29662190/

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