为volatile和非volatile实例重载类

时间:2012-12-13 19:59:08

标签: c++ overloading volatile

我正在编写一个需要同时支持volatile和非易失性实例的类(volatile实例使用原子操作,非易失性实例使用常规操作),我想知道我是否以正确的方式处理它。到目前为止,这是关于类声明的嗤之以法:

class Yield {
public:
    Yield();
    Yield(Yield const &other);
    Yield(Yield const volatile &other);

    Yield &operator=(Yield const &other);
    Yield &operator=(Yield const volatile &other);

    Yield &operator+=(Yield const &other);
    Yield &operator+=(Yield const volatile &other);
    Yield volatile &operator+=(Yield const &other) volatile;
    Yield volatile &operator+=(Yield const volatile &other) volatile;

    // Other operators snipped...
};
  • 问题1:使用MSVC进行编译时,收到以下警告:

    warning C4521: 'util::Yield' : multiple copy constructors specified

    此警告是否预示到使用此类时出现的任何问题?或者可以安全地忽略它?

  • 问题2:就目前而言,所有运算符都会因易失性和非易失性other参数而过载。我认为这是必要的,以避免非易失性实例的较慢的易失性访问?有没有替代方法允许每个方法只编码两次(易失性lhs和非易失性lhs)而不是4次(易失性和非易失性lhs,每个都有易失性和非易失性rhs)?

我希望将这些问题放在一起是好的,否则请留言,我可以将它们分开。 谢谢!

2 个答案:

答案 0 :(得分:3)

  

该类具有单个类型的多个副本构造函数。这个警告是信息性的;构造函数可以在程序中调用。

来自msdn网站:Compiler Warning (level 3) C4521

答案 1 :(得分:2)

Volatile does not do what you think it does

即使使用VC ++特殊的非标准volatile行为,也会导致代码比正确编写代码慢。使用std::atomic,或者如果没有,那么您可能已经获得了特定于平台的屏障,围栅和原子内在函数。 VC ++有_ReadWriteBarrier_Interlocked函数可以帮助您。