构造函数形参默认值,用make_unique创建对象,形参默认值失效。
而改为new就可以
class VBase
{
public:
VBase(){}
virtual ~VBase(){}
public:
virtual void Handle() = 0;
protected:
};
class Transfer : public VBase
{
public:
Transfer(const int& currDate = 20220209):m_currDate(currDate)
{
std::cout << m_currDate << std::endl;//此处有值20220209
}
~Transfer(){}
virtual void Handle()
{
std::cout << m_currDate << std::endl;//值为0
}
private:
const int& m_currDate; //是不是加了引用的问题
};
int main()
{
std::unique_ptr<VBase> pTrans = std::make_unique<Transfer>();
pTrans->Handle(); // 打印 0
VBase* pNew = new Transfer(); // 输出20220209
return 0;
}
构造函数中打印 20220209
Handle中打印 0
private:
const int& m_currDate; //是不是加了引用的问题
此处的引用去掉就能达到预期效果,但是不知道是为什么。
而且为什么成员变量用引用,采用new的方式就能达到预期效果
构造函数中打印 20220209
Handle中打印 20220209
如果你要绑定引用,你得确保你所绑定的对象一直存在。
当用缺省参数调用Transfer
构造函数时,编译器创建了一个临时变量值为20220209,参数currDate和成员变量m_currDate都绑定到这个临时变量,当构造函数返回时,这个临时变量被释放了,因此m_currDate引用也就失效了。
解决方法有两种:
class Transfer {
public:
static const int default_date;
Transfer(const int ¤tDate = default_date) : m_currentDate(currentDate) {
// ...
}
// ...
private:
const int &m_currDate;
};
const int Transfer::default_date = 20220209;