gpt4 book ai didi

c++ - 带有 CRITICAL_SECTION 的模板类编译但在使用时出现错误

转载 作者:太空宇宙 更新时间:2023-11-04 11:50:46 25 4
gpt4 key购买 nike

我的库中有这些类。

class SingleLock
{
public:
SingleLock(CRITICAL_SECTION *pCS);
~SingleLock();

private:
LPCRITICAL_SECTION m_cs;
};

SingleLock::SingleLock(CRITICAL_SECTION *pCS)
{
m_cs = pCS;
EnterCriticalSection(m_cs);
}
SingleLock::~SingleLock()
{
LeaveCriticalSection(m_cs);
}

template <typename T>
class Callback
{
public:
Callback() : m_current(), m_total(), m_cs()
{
InitializeCriticalSection(&m_cs);
}

~Callback()
{
DeleteCriticalSection(&m_cs);
}

void SetCurrent(T current)
{
SingleLock(&m_cs);
m_current = current;
}

void SetTotal(T total)
{
SingleLock(&m_cs);
m_total = total;
}

T GetCurrent()
{
SingleLock(&m_cs);
return m_current;
}

T GetTotal()
{
SingleLock(&m_cs);
return m_total;
}

private:
T m_total;
T m_current;
CRITICAL_SECTION m_cs;
};

Callback 类可以编译,但是尝试在代码中使用某些方法时,我的代码无法编译。我把它改成了这样:

template <typename T>
class Callback
{
public:
Callback() : m_current(0), m_total(0), m_cs()
{
InitializeCriticalSection(&m_cs);
}

~Callback()
{
DeleteCriticalSection(&m_cs);
}

void SetCurrent(T current)
{
EnterCriticalSection(&m_cs);
m_current = current;
LeaveCriticalSection(&m_cs);
}

void SetTotal(T total)
{
EnterCriticalSection(&m_cs);
m_total = total;
LeaveCriticalSection(&m_cs);
}

T GetCurrent()
{
EnterCriticalSection(&m_cs);
T result = m_current;
LeaveCriticalSection(&m_cs);
return result;
}

T GetTotal()
{
EnterCriticalSection(&m_cs);
T result = m_total;
LeaveCriticalSection(&m_cs);
return result;
}

private:
T m_total;
T m_current;
CRITICAL_SECTION m_cs;
};

现在一切正常,有人可以解释为什么会这样吗?

最佳答案

对此不满意,但在发布问题后立即发现错误,我需要 SingleLock sl(&m_cs); 而不是 SingleLock(&m_cs);

关于c++ - 带有 CRITICAL_SECTION 的模板类编译但在使用时出现错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18375017/

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