临时对象与复制构造函数问题
秦帅 2019-04-06 10:59:14 #include"Stringbad.h"
#include<cstring>
int stringbad::numbers = 0;
stringbad::stringbad()
{
numbers++;
len = 4;
str = new char[len];
strcpy(str, "c++");
std::cout << "is numebr " << numbers << " " << str << std::endl;
}
stringbad::stringbad(const char * s)
{
numbers++;
len = strlen(s);
str = new char[len + 1];
strcpy(str, s);
std::cout << "is numebr " << numbers << " " << str << std::endl;
}
std::ostream& operator<<(std::ostream &os, const stringbad & a)
{
os << a.str << std::endl;
return os;
}
stringbad::~stringbad()
{
numbers--;
std::cout << "numebr is" << numbers << " is delete " << str << std::endl;
delete[]str;
}
stringbad a = "i will find you";
cout << a;
当我如此创建stringbad对象,先调用构造函数生成临时对象,然后会调用默认复制构造函数,但我认为在cout前,临时对象已经被delete,所以cout<<a输出会出问题,但经过测试,输出没有问题。这是为何?