homework-08
1. 理解C++变量的作用域和生命周期
a) 用少于10行代码演示你对局部变量的生命周期的理解
#include <iostream> int* local1(int i){ int p = i; return &p; //会导致指针悬空,p是局部变量,函数结束空间就被回收 } int main(){ int *p,*q; p = local1(1); std::cout << *p; //虽然能得到p=1 但是这是个错误 return 0; }
2. 理解堆和栈,两种内存的申请和释放的方式
a) 用少于30行代码演示你对堆和栈两种内存申请方式的理解
1、栈区(stack):由编译器自动分配释放,存放函数的参数值,局部变量的值等,其操作方式类似于数据结构的栈。
2、堆区(heap):一般是由程序员分配释放,若程序员不释放的话,程序结束时可能由OS回收,值得注意的是他与数据结构的堆是两回事,分配方式倒是类似于数据结构的链表。
有一个博客讲得比较好 http://www.cnitblog.com/guopingleee/archive/2009/02/16/54601.html
int a[100]; //系统自动分配到栈空间,函数结束就被回收 int *b = new int[100]; //手动开在堆空间上,需要显式用delet删除 delete [] b;
3. 理解unique_ptr和shared_ptr
a) http://msdn.microsoft.com/en-us/library/vstudio/hh279676.aspx
b) http://msdn.microsoft.com/en-us/library/vstudio/hh279669.aspx
unique_ptr是一种定义在<memory>中的智能指针(smart pointer)。它持有对对象的独有权——两个unique_ptr不能指向一个对象,不能进行复制操作只能进行移动操作。
shared_ptr的作用有如同指针,但会记录有多少个shared_ptrs共同指向一个对象。这便是所谓的引用计数(reference counting)。一旦最后一个这样的指针被销毁,也就是一旦某个对象的引用计数变为0,这个对象会被自动删除。这在非环形数据结构中防止资源泄露很有帮助。
4. 请尝试用“C++0x”,“C++11 & STL”两种不同的代码风格分割一个url,并上传代码到博客上。
For example:
Input: http://msdn.microsoft.com/en-us/library/vstudio/hh279674.aspx
Output: http, msdn, Microsoft, com, en-us, library, vstudio, hh279674, aspx
#include<iostream> #include<string> #include<vector> #include "parse.h" using namespace std; int main(){ std::string x; std::cout<< "please input a url:"; std::cin>>x; Parse p; p.start(x); for(auto i = p.as.begin();; i++){ //使用auto自动类型推导 推出i是vector<string>的迭代器 cout<<*i; if(i+1 == p.as.end()){ break; } else cout<<","; } }
#pragma once #include<string> #include<vector> #include<iostream> class Parse { public: std::vector<std::string> as; public: Parse(void); ~Parse(void); void start(std::string ss); };
#include "parse.h" Parse::Parse() { } void Parse::start(std::string s) { int i=0,n=s.size(); while(true){ if(s[i]== '.' || s[i]== '/' || s[i]==':'){ //遇到'.' '/' 就跳过 i++; continue; } std::string word = ""; while(true){ if(s[i]== '.' || s[i]== '/' || s[i]==':') break; word = word+s[i]; i++; if(i == n) break; } as.push_back(word); if(i == n) break; } } Parse::~Parse(void) { }
运行结果