临时操作符重载

Operator overloading on temporary

本文关键字:重载 操作符      更新时间:2023-10-16

我在尝试对方法返回的临时对象使用位移运算符时遇到了一些问题。

这个想法是创建一个Log对象作为临时对象,并通过bitshift操作符,附加将存储在std::stringstream对象中的值。

在销毁临时对象时,std::stringstream将转储其内容,但是,在追加第一个字符串之前调用析构函数。

一个小例子:

class LogEntry
{
public:
    LogEntry(int level) : m_level{level}
    {
    }
    ~LogEntry()
    {
        // dump m_out on destruction
        Widget(m_out.str());
    }
    template <typename T>
    LogEntry& operator<<(T& arg)
    {
        m_out << arg;
        return *this;
    }
private:
    std::stringstream m_out;
    const int m_level;
}

我打算这样使用它:

LogEntry(LOG_LEVEL_DEFAULT) << "This is a string" << 1234;

到目前为止,析构函数是在位移操作符之前调用的,这意味着在将内容追加到m_out时内存已经损坏。

有谁知道如何确保在临时对象销毁之前调用操作符吗?

正如@hvd和@Richard Critten在评论中指出的那样,您的代码无法编译。如果想要一个只存在于语句中的临时变量,可以不给它命名,比如:

LogEntry(LOG_LEVEL_DEFAULT) << "This is a string" << 1234;

如果这样做,将在调用析构函数之前调用这两个操作符。

但是还有一个问题。你的operator<& lt; (T&arg)接受一个左值引用作为输入,而1234不是一个左值。要解决第二个问题,可以将操作符更改为将一个通用引用作为参数:operator<<(T&&)arg)。