C4512 无法生成赋值运算符

C4512 assignment operator could not be generated

我正在更新一个旧的 C++ 应用程序,它是用 MSVC 2013 编译的,不是我知道的最新版本。

我收到警告:

1>c:\fraenkelsoftware-millikan\shared\debug\debughelper.h(84): warning C4512: 'HowLong' : assignment operator could not be generated
1>          c:\fraenkelsoftware-millikan\shared\debug\debughelper.h(65) : see declaration of 'HowLong'

这是 class 原型:

class HowLong {
public:
    /// \param  Duration of what we are trying to measure
    HowLong(const std::string &a_str, IDebug::Severity a_sev = Sev_Debug):
            m_start(boost::posix_time::microsec_clock::universal_time()),
                m_str(a_str), m_sev(a_sev) {
    }
    /// Destructor outputs how long the object was alive
    ~HowLong() {
        boost::posix_time::time_duration elapsed(boost::posix_time::microsec_clock::universal_time() - m_start);
        DEBUG_LOG(m_sev, m_str + " took: " + boost::posix_time::to_simple_string(elapsed));
    }

private:
    const boost::posix_time::ptime m_start; ///< Start time
    const std::string m_str;                ///< Duration of what we are trying to measure
    const IDebug::Severity m_sev;
};

我以前从未见过此警告,我不确定它的实际含义?

class 具有常量私有数据成员

const boost::posix_time::ptime m_start; ///< Start time
const std::string m_str;                ///< Duration of what we are trying to measure
const IDebug::Severity m_sev;

您不能重新分配常量对象。因此编译器发出一条消息,它无法生成进行 member-wise 赋值的默认复制赋值运算符。

不同的例子,相似的效果:

struct foo { const int x = 42;};

int main() {
    foo f,g;
    f = g;
}

foo 没有编译器生成的赋值运算符,因为您不能分配给 const 成员。

但是,在上面它会导致错误(g 不能分配给 f)。我不得不承认,我不知道如何只获得警告,我想实际触发警告的代码不在您发布的部分中。