临时对象与复制构造函数问题

秦帅 秦帅 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
#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输出会出问题,但经过测试,输出没有问题。这是为何?
...全文

相关推荐

评论 5
收藏 已收藏
分享
返回顶部
秦帅
C++ 语言 65,214 成员 250,514 内容