2.10. 练习
You can buy solutions to all exercises in this book as a ZIP file.
- 使用适当的智能指针优化下面的程序:
- #include <iostream>
- #include <cstring>
- char *get(const char *s)
- {
- int size = std::strlen(s);
- char *text = new char[size + 1];
- std::strncpy(text, s, size + 1);
- return text;
- }
- void print(char *text)
- {
- std::cout << text << std::endl;
- }
- int main(int argc, char *argv[])
- {
- if (argc < 2)
- {
- std::cerr << argv[0] << " <data>" << std::endl;
- return 1;
- }
- char *text = get(argv[1]);
- print(text);
- delete[] text;
- }
- 下载源代码
- 优化下面的程序:
- #include <vector>
- template <typename T>
- T *create()
- {
- return new T;
- }
- int main()
- {
- std::vector<int*> v;
- v.push_back(create<int>());
- }