#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;
}
My expectation is to call both default and copy constructor, but only default constructor is called. What might be the issue??
The output is: default construcor called
Copy constructing a shared pointer calls the copy constructor of the shared pointer. This
std::shared_ptr<Init> b(a);is not constructing anInit. Instead it constructs ashared_ptrthat shares ownership withaof the sameInitinstance. In your code only a singleInitinstance is created. Sharing ownership of one instance is the purpose of having multiple copies of a shared pointer.Init(std::shared_ptr<Init> z)is not a copy constructor. A copy constructor isInit(const Init&)(which is also not used in your code).It isnt obvious what you actually wanted to do, however, this is how you can create a second
shared_ptrthat manages the lifetime of a secondInitinstance which is copy constructed from the first:output:
Live Demo
PS:
Init(int y)is not a default constructor. A default constructor is one that can be called without arguments, egInt(int y=0)would be a default constructor.