homework-08
一、C++变量的作用域和生命周期
#include<iostream> using namespace std; //C++变量的作用域和生命周期 void test1() { for(int i=0 ; i<5 ; i++) cout<<i<<endl; } void main() { test1(); system("pause"); }
输出:
#include<iostream> using namespace std; //C++变量的作用域和生命周期 void test1() { for(int i=0 ; i<5 ; i++) ; } void main() { int i = 0; test1(); cout<<i<<endl; system("pause"); }
输出:
二、堆和栈两种内存的申请和释放的方式
#include<iostream> using namespace std; //堆和栈两种内存申请方式 void main() { int a; //栈的申请方式 ,程序结束后系统自动释放 char *p1; //堆的申请方式 p1 = (char *)malloc(10); free(p1); }
三、unique_ptr和shared_ptr
unique_ptr:
unique_ptr指针不能进行复制操作,只能进行移动操作;不能按值传递给一个函数;也不能应用在任何需要复制操作的标准模板库(STL)的算法上。unique_ptr指向的对象被破坏或对象通过operator=()或reset()被指定到另一个指针时才能被销毁。
shared_ptr:
shared_ptr是一种专为场景中可能同时有多个所有者来管理内存中对象的寿命的智能指针,shared_ptr会记录有多少个shared_ptrs共同指向一个对象,当有新的智能指针加入、退出或是复位,控制块计数器做出相应改变,当控制块引用计数达到零,则控制块中删除相应的内存资源还有它本身。
四、分割url
#include<iostream> #include<string.h> using namespace std; //分割url c++0x class URL { private: char str[100]; char word[20][20]; int count; public: void input(); void work(); void ouput(); }; void URL::input() { char ch; int i=0; printf("请输入url:"); while((ch=cin.get())!='\n') str[i++]=ch; str[i] = '\0'; } void URL::work() { int i = 0; int row = 0; while(str[i]!='\0') { if(str[i]!=':' && str[i]!='/' && str[i]!='.' && str[i] !='\0') { int col = 0; while(str[i]!=':' && str[i]!='/' && str[i]!='.' && str[i] !='\0') word[row][col++]=str[i++]; word[row][col]='\0'; row++; } else i++; } count = row; } void URL::ouput() { int row; for(row = 0;row < count-1;row++) printf("%s,",word[row]); printf("%s\n",word[row]); } void main() { URL url; url.input(); url.work(); url.ouput();
system("pause");
}
#include<iostream> #include <string.h> //用STL进行字符串的分割 void main() { int i; int row; char ch; char str[100]; char word[20][20]; std::cout<<"请输入url:"; for(i = 0;(ch=std::cin.get())!='\n';i++) str[i] = ch; str[i] = '\0'; i = 0; row = 0; while(str[i]!='\0') { if(str[i]!=':' && str[i]!='/' && str[i]!='.' && str[i] !='\0') { int col = 0; while(str[i]!=':' && str[i]!='/' && str[i]!='.' && str[i] !='\0') word[row][col++]=str[i++]; word[row][col]='\0'; row++; } else i++; } for(i = 0;i < row-1;i++) std::cout<<word[i]<<","; std::cout<<word[i]<<std::endl; system("pause"); }