【问题标题】:volatile member can not be accessed by member functionvolatile成员不能被成员函数访问
【发布时间】:2014-02-18 09:59:30
【问题描述】:

以下代码使我的程序崩溃:

#include <string>
#include <vector>

class test {
volatile std::vector<std::string> wtf;
public:
    test() {}
    void dope() { wtf.clear(); }
};

int main(){
    (new test())->dope();
    return 0;
}

我也不知道为什么。当我删除 volatile 时,它​​会再次起作用。那么为什么 volatile 是个问题呢?

【问题讨论】:

  • 我认为真正的问题是你为什么想要volatile std::vector?
  • 我得到了(使用 gcc 4.8.1):error: passing 'volatile std::vector&lt;std::basic_string&lt;char&gt; &gt;' as 'this' argument of 'void std::vector&lt;_Tp, _Alloc&gt;::clear() [with _Tp = std::basic_string&lt;char&gt;; _Alloc = std::allocator&lt;std::basic_string&lt;char&gt; &gt;]' discards qualifiers [-fpermissive]
  • 它包含程序每次都必须访问的信息。而且它是多线程的。
  • 为什么是volatilestd::vectorvolatile 是没有意义的。
  • Volatile 不会像你想象的那样做。

标签: c++ crash volatile


【解决方案1】:

std::vector::clear() 没有 volatile 限定符。

所以用 volatile 向量调用它是非法的。

顺便说一句,volatile 不是多线程的神奇关键字。
您可以使用mutex 来保护对您的向量的访问。

【讨论】:

    猜你喜欢
    • 2021-11-13
    • 2014-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-16
    • 2015-04-01
    • 2023-03-24
    相关资源
    最近更新 更多