When I create an array of shared_ptrs to object Foo
, what is actually being created?
class Foo {
public:
Foo() x(3) : {};
int x;
}
std::array<std::shared_ptr<Foo>, 10> arr_;
For instance, will the following code print 3?
std::shared_ptr<Foo> ptr = arr_[0];
std::cout << ptr->x;
Or do I first need to use make_shared
and if so why?
std::shared_ptr<Foo> ptr = arr_[0];
ptr = make_shared<Foo>();
std::cout << ptr->x;
So here's a small example to show that their default constructor stores
nullptr
.Output
No, it will dereference a
nullptr
and this is an undefined behavior (Usually, it is likely to cause a crash).