繁体   English   中英

STL作为静态易失成员的问题

[英]Problems with STL as a static volatile member

我正在尝试编译如下内容:


#include <list>

class thread
{
public:
 static volatile std::list<thread *> threadList;    //This is also protected by a mutex
};
volatile std::list<thread *> thread::threadList;

void main()
{
 thread A;
 thread::threadList.push_back(&A);
 thread::threadList.remove(&A);
}

尝试编译时出现以下错误:


test.cpp(14): error C2663: 'std::list::push_back' : 2 overloads have no legal conversion for 'this' pointer
          with
          [
              _Ty=thread *
          ]
test.cpp(15): error C2662: 'std::list::remove' : cannot convert 'this' pointer from 'volatile std::list' to 'std::list &'
          with
          [
              _Ty=thread *
          ]
          Conversion loses qualifiers

我究竟做错了什么?
编辑:修复了一些<和>格式错误
EDIT2:threadList受互斥锁保护,为简单起见,我没有将其放在此处

除去挥发物并消除问题。 因此,对于真正的答案,如果您解释为什么需要波动及其在此处的含义,可能会有所帮助。 它不会使整个列表都被视为易变的。

另请参阅先前的答案

首先, volatile可能是最难理解的关键字,而且它很可能没有按照您的想法去做。 我是很难学的。

话虽这么说,问题在于volatile也可以用作函数的限定符,以确保在正确的上下文中调用它们。 push_back()函数未使用volatile限定符声明,因此在volatile对象上调用该函数无效。 非易失性成员函数只能为非易失性对象调用。

使用g ++编译得到

test.cpp:13:错误:将'volatile std :: list>'作为'void std :: list <_Tp,_Alloc> :: push_back(const _Tp&)['_Tp = thread *,_Alloc = std :: allocator]'丢弃限定符...

discards qualifiers是您的提示。 函数list::push_back不能在constvolatile实例上调用。

一种方法是:

  • 将清单设为私人
  • 创建一个私有的静态互斥体
  • 创建addremove的静态公共函数
  • addremove获取锁,然后从列表中添加或删除

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM