Tag Archives: c++

C++ Boost智能指针小测

请阅读该文档(http://www.boost.org/doc/libs/1_49_0/libs/smart_ptr/shared_ptr.htm),回答以下问题: boost::shared_ptr能存放数组指针吗?如果不能,应该使用什么? 与std::auto_ptr相比,boost::shared_ptr有什么优势? 对于一般指针的dynamic_cast,boost::shared_ptr应该怎么cast? 什么情况下使用shared_from_this? 如何获取shared_ptr中保存的具体对象的指针? 如果要释放某shared_ptr对指针的引用,应该怎么操作? 什么情况使用weak_ptr? shared_ptr怎么管理file, MYSQL_RES, CURL等资源?

C++程序注意事项

智能指针 为了避免 遗忘释放内存、资源 中途return,需要多处调用释放内存,资源 放到容器中的指针,错误释放内存,资源 我们写c++程序时,都使用智能指针来帮助管理内存和资源。c++不是c,提供的便捷要利用起来: 不使用任何明确的delete语句 熟悉并熟练使用 std::auto_ptr, boost::shared_ptr, boost::shared_array, boost::scoped_ptr, boost::scoped_array Don’t 动态分配内存,不要使用以下方法. 因为 1 处会抛出异常造成delete无法释放。 int n = 100; char *p = new char[n]; ….// 1: 使用p delete []p; Do 使用以下任一方法分配、管理内存 int n = 100; std::vector v; v.resize(n); ….// 使用 &v.at(0)或者&v[0], 与上面的p等价 // 不需要调用delete[] 或者 int n = 100; boost::shared_array p(new char[n]); [...]

c++版本的普通程序员,文艺程序员,2b程序员和失足程序员

逆序输出字符串 普通程序员 #include <iostream> using namespace std; char *str = “n!dlrow olleh”; int main (int argc, char** argv) { for(char *p = str + strlen(str); p >= str; p–){ cout << *p; } return 0; } 文艺程序员 #include <iostream> #include <iterator> #include <algorithm> using namespace std; static char *str = “n!dlrow olleh”; int main (int [...]