• 2.10. 练习

    2.10. 练习

    You can buy solutions to all exercises in this book as a ZIP file.

    • 使用适当的智能指针优化下面的程序:
    1. #include <iostream>
    2. #include <cstring>
    3.  
    4. char *get(const char *s)
    5. {
    6. int size = std::strlen(s);
    7. char *text = new char[size + 1];
    8. std::strncpy(text, s, size + 1);
    9. return text;
    10. }
    11.  
    12. void print(char *text)
    13. {
    14. std::cout << text << std::endl;
    15. }
    16.  
    17. int main(int argc, char *argv[])
    18. {
    19. if (argc < 2)
    20. {
    21. std::cerr << argv[0] << " <data>" << std::endl;
    22. return 1;
    23. }
    24.  
    25. char *text = get(argv[1]);
    26. print(text);
    27. delete[] text;
    28. }
    • 下载源代码
      • 优化下面的程序:
    1. #include <vector>
    2.  
    3. template <typename T>
    4. T *create()
    5. {
    6. return new T;
    7. }
    8.  
    9. int main()
    10. {
    11. std::vector<int*> v;
    12. v.push_back(create<int>());
    13. }
    • 下载源代码