c++ 为什么不调用复制构造函数?

f87krz0w  于 2023-06-25  发布在  其他
关注(0)|答案(1)|浏览(194)
  1. #include <iostream>
  2. #include <memory>
  3. using namespace std;
  4. class Init {
  5. private:
  6. int x;
  7. public:
  8. Init(int y) {
  9. x = y;
  10. cout << "default constructor called" << endl;
  11. }
  12. Init(std::shared_ptr<Init> z) {
  13. this->x = z->x;
  14. cout << "copy constructor called" << endl;
  15. }
  16. };
  17. int main()
  18. {
  19. int k = 5;
  20. std::shared_ptr<Init> a = std::make_shared<Init>(k);
  21. std::shared_ptr<Init> b(a);
  22. return 0;
  23. }

我的期望是调用default和copy构造函数,但只调用default构造函数。可能是什么问题呢??
输出为:默认构造函数调用

91zkwejq

91zkwejq1#

复制构造共享指针调用共享指针的复制构造函数。这个std::shared_ptr<Init> b(a);不是在构造Init。相反,它构造了一个shared_ptr,与a共享同一Init示例的所有权。在代码中,只创建了一个Init示例。共享一个示例的所有权是拥有共享指针的多个副本的目的。
Init(std::shared_ptr<Init> z)不是复制构造函数。一个复制构造函数是Init(const Init&)(在您的代码中也没有使用)。
你实际上想做什么并不明显,但是,这就是你如何创建第二个shared_ptr来管理第二个Init示例的生存期,该示例是从第一个示例复制构造的:

  1. #include <iostream>
  2. #include <memory>
  3. // better not using namespace std;
  4. class Init {
  5. private:
  6. int x;
  7. public:
  8. Init(int y) : x(y){ // <--- use member initializer list for initialization
  9. std::cout << "default constructor called\n";
  10. }
  11. Init(const Init& other) : x(other.x) { // <--- copy constructor
  12. std::cout << "copy constructor called\n";
  13. }
  14. };
  15. int main()
  16. {
  17. int k = 5;
  18. std::shared_ptr<Init> a = std::make_shared<Init>(k);
  19. std::shared_ptr<Init> b = std::make_shared<Init>(*a);
  20. // return 0; // not needed here
  21. }

输出:

  1. default constructor called
  2. copy constructor called

Live Demo
PS:Init(int y)不是默认构造函数。默认构造函数是可以在没有参数的情况下调用的构造函数,例如Int(int y=0)是默认构造函数。

展开查看全部

相关问题