C++中的初始化与赋值

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

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 }

posted on 2011-05-24 11:47  Joshua Leung  阅读(334)  评论(0编辑  收藏  举报

导航