1

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

我以前没有看到过这个警告,我不确定它的实际含义是什么?

4

2 回答 2

3

该类具有恒定的私有数据成员

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;

您不能重新分配常量对象。所以编译器发出一条消息,它无法生成一个默认的复制赋值运算符来进行成员分配。

于 2020-08-19T11:31:27.953 回答
2

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

struct foo { const int x = 42;};

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

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

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

于 2020-08-19T11:32:09.530 回答