临时操作符重载
Operator overloading on temporary
我在尝试对方法返回的临时对象使用位移运算符时遇到了一些问题。
这个想法是创建一个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)。
相关文章:
- 重载操作符+:表达式必须是整型或无作用域枚举类型
- 重载操作符
- 如何重载操作符==外模板类使用友元函数
- 重载*操作符,使其在左右两边都工作
- 重载操作符<对于非随机迭代器
- 在c++中重载操作符的时间和原因
- 如何在c++中重载=操作符来通过引用进行复制
- 如何在c++中获取定义为友元的重载操作符的地址
- 使用重载操作符的文件操作表达式没有给出预期的结果
- 重载操作符()
- 重载操作符()并在类内使用
- 类中的重载操作符+
- 定时使用重载操作符
- c++带类的重载操作符
- 用列表容器重载[]操作符
- 重载操作符=
- 任何重载操作符()的静态检测
- 重载操作符以处理类对象
- 在使用另一个类的类中重载操作符==
- 派生类和基类中的重载操作符不同