我在尝试对方法返回的临时对象使用位移运算符时遇到了一些问题。
想法是创建一个临时的 Log 对象,并通过位移运算符附加将存储在 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 时内存已经损坏。
有谁知道如何确保在临时对象销毁之前调用运算符(operator)?
最佳答案
正如@hvd 和@Richard Critten 在评论中指出的那样,您的代码无法编译。如果你想要一个只存在于语句中的临时变量,你可以不给它一个名字,比如:
LogEntry(LOG_LEVEL_DEFAULT) << "This is a string" << 1234;
如果你这样做,这两个运算符将在调用析构函数之前被调用。
但是还有一个问题。您的 operator<<(T& arg) 将左值引用作为输入,而 1234 不是左值。要解决第二个问题,您可以更改运算符以将通用引用作为参数:operator<<(T&& arg)。
关于c++ - 运算符临时重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40387151/