C++中的初始化与赋值

本文通过一个C++字符串类的实例,演示了未初始化存储区进行用户自定义赋值操作可能导致的问题,强调了正确初始化对象的重要性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

永远不要对一个未被初始化的存储区执行用户自定义的赋值操作,且看:

1 #include <stdio.h>
2 #include <string.h>
3
4  class String{
5 public:
6 String(const char *init){
7 if(!init) init = "";
8 s_ = new char[strlen(init) + 1];
9 strcpy(s_,init);
10 }
11 ~String(){
12 delete [] s_;
13 }
14 String &operator=(const char *str){
15 if(!str) str = "";
16 char *tmp = strcpy(new char[strlen(str) + 1],str);
17 if(!s_)
18 printf("s_ is NULL, you cannot delete it!\r\n");
19 delete [] s_;
20 s_ = tmp;
21 return *this;
22 }
23 private:
24 char *s_;
25 };
26 int main(int argc, char **argv)
27 {
28 String *names = static_cast<String *>(::operator new(100));
29 names[0] = "Sakamoto";
30 // it is very likely that you get a weird output!
31 printf("The value of names is :%s\n",names);
32 return 0;
33 }

转载于:https://www.cnblogs.com/cmleung/archive/2011/05/24/2055229.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值