//serialport.h
class SerialPort
{
public:
SerialPort(boost::asio::io_service &ios, boost::asio::serial_port &port);
SerialPort &operator=(const SerialPort &o); //重写 operator=
private:
boost::asio::io_service &m_ios;
boost::asio::serial_port &m_port;
};
//serialport.cpp
#include "serialport.h"
SerialPort::SerialPort(boost::asio::io_service &ios, boost::asio::serial_port &port): m_ios(ios), m_port(port) //compile OK
{
}
//方式一 (结果编译不过去)
SerialPort &SerialPort::operator=(const SerialPort &o) //重写operator=
{
m_ios = &o.m_ios; //error!
m_port = &o.m_port; //error!
return *this;
}
//error: no match for "operator=" (operand types are "boost::asio::io_service" and "boost::asio::io_service*") m_ios = &o.m_ios;
//方式二 (结果编译不过去)
SerialPort &SerialPort::operator=(const SerialPort &o) //重写operator=
{
m_ios = o.m_ios; //error! Why?
m_port = o.m_port; //error! Why?
return *this;
}
//error: use of deleted function "boost::asio::io_service& boost::asio::io_service::operator=(const boost::asio::io_service&)" m_ios = o.m_ios;
问题: 本人应该怎么正确重写这个 operator= 呢?谢谢各位!
解决方案
5
SerialPort &SerialPort::operator=(const SerialPort &o) //重写operator=
{
this->~SerialPort();
this->SerialPort(o.xxx, o.yyyy);
return *this;
}
手动调用析构/构造函数
5
然而这么写还是错的
SerialPort &SerialPort::operator=(const SerialPort &o) //重写operator=
{
this->~SerialPort();
//直接调用,构造函数,重新构造对象本人,
//用placement new ,似乎比较正常一点
new(this) SerialPort(o.xxx, o.yyyy);
return *this;
}
试试看
3
《C++编程思想》