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 }

原文链接: https://www.cnblogs.com/cmleung/archive/2011/05/24/2055229.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/26029

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月8日 上午3:47
下一篇 2023年2月8日 上午3:47

相关推荐