C4512赋值运算符无法生成

问题描述

我正在更新一个旧的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 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;
};

我以前没有看过这个警告,也不确定它到底意味着什么?

解决方法

该类具有不变的私有数据成员

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;

您不得重新分配常量对象。因此,编译器发出一条消息,提示它无法生成进行成员分配的默认副本分配运算符。

,

不同的示例,效果相似:

struct foo { const int x = 42;};

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

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

但是,在上面它导致错误(无法将g分配给f)。我不得不承认,我不知道如何仅获得警告,并且我认为确实触发警告的代码不在您发布的部分中。