c++ - 在赋值期间,如何使volatile结构表现得完全像volatile int?

标签 c++ struct volatile

当从非 Volatile volatile int分配给int时,编译器。当从相同类型的非 Volatile volatile struct中的struct中分配代码时,编译器似乎非常不满意。

考虑下面的简单程序。

struct Bar {
    int a;
};

volatile int foo;
int foo2;

volatile Bar bar;
Bar bar2;

int main(){
    foo = foo2;
    bar = bar2;
}

当我尝试编译此代码时,在main的第二行而不是第一行出现错误。
g++     Main.cc   -o Main
Main.cc: In function ‘int main()’:
Main.cc:13:9: error: passing ‘volatile Bar’ as ‘this’ argument discards qualifiers [-fpermissive]
     bar = bar2;
         ^
Main.cc:1:8: note:   in call to ‘Bar& Bar::operator=(const Bar&)’
 struct Bar {

似乎出现了问题,因为volatile Bar传递到了赋值运算符的左侧,尽管我不确定为什么这不是int的问题。

我查看了this answer,它提出了以下修复措施。
struct Bar {
    int a;
    volatile Bar& operator= (const Bar& other) volatile {
       *this = other; 
    }
};

不幸的是,这导致了以下两个警告。
g++     Main.cc   -o Main
Main.cc: In member function ‘volatile Bar& Bar::operator=(const Bar&) volatile’:
Main.cc:4:21: warning: implicit dereference will not access object of type ‘volatile Bar’ in statement
        *this = other; 
                     ^
Main.cc: In function ‘int main()’:
Main.cc:16:15: warning: implicit dereference will not access object of type ‘volatile Bar’ in statement
     bar = bar2;

然后,我查看了this answer,其中提到我应该将引用转换为一个右值,但是我不确定要转换的引用以及在这种情况下要使用的转换语法。

是什么正确的咒语才能使main的第2行的行为与main的第1行完全一样,而没有警告或错误?

最佳答案

您最初的问题是因为隐式赋值运算符具有签名

Bar& operator=(const Bar& rhs);

...而volatile对象则无法调用。警告是因为更新后的函数返回了 Volatile 引用,但是从未使用过该引用。 GCC认为这可能是个问题。解决此问题的最简单方法是将返回类型更改为void!

还有另一个问题:您的函数将以无限递归方式进行调用。我建议以下内容:
struct Bar {
    int a;
    Bar& operator=(const Bar&rhs) = default;
    void operator=(const volatile Bar& rhs) volatile // Note void return.
    {
         // Caution: This const_cast removes the volatile from
         // the reference.  This may lose the point of the original
         // volatile qualification.
         //
         // If this is a problem, use "a = rhs.a;" instead - but this
         // obviously doesn't generalize so well.
         const_cast<Bar&>(*this) = const_cast<const Bar&>(rhs);
    }
};

volatile Bar vbar;
Bar bar;

int main(){
    vbar = bar;  // All four combinations work.
    bar = vbar;
    vbar = vbar;
    bar = bar;
    return 0;
}

这意味着在使用 Volatile 结构时,您将无法链接分配运算符。我断言这不是很大的损失。

最后一点:为什么要使用volatile-它对多线程代码不是很有用(它对内存映射IO很有用)。

关于c++ - 在赋值期间,如何使volatile结构表现得完全像volatile int?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39995280/

相关文章:

c++ - 遍历结构内部的数组

ios - 细化 Swift API GET 函数

java - 即使两个线程不同时读写,我是否也需要同步?

c++ - 我的简单 C 程序出现内存错误

c++ - 你如何将 CString 和 std::string std::wstring 相互转换?

c - 如何接受字符数组输入到 C 结构中?

c# - 多处理器系统中 volatile 关键字的成本是多少?

c++ - 使函数返回具有不同属性的东西

c++ - 调用构造函数初始化变量

c++ - volatile 关键字和 RAII 习语 (C++)