小编cha*_*ndu的帖子

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

#include <iostream>
#include <memory>

using namespace std;

class Init {
private:
    int x;
public:
    Init(int y) {
        x = y;
        cout << "default constructor called" << endl;
        
    }
    
    Init(std::shared_ptr<Init> z) {
        this->x = z->x;
        cout << "copy constructor called" << endl;
    }
};

int main()
{
    int k = 5;
    std::shared_ptr<Init> a = std::make_shared<Init>(k);
    std::shared_ptr<Init> b(a);

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我的期望是同时调用默认构造函数和复制构造函数,但只调用默认构造函数。可能是什么问题?

输出是: 默认构造函数称为

c++ smart-pointers copy-constructor shared-ptr default-constructor

1
推荐指数
1
解决办法
126
查看次数