1

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;
genpfault
  • 51,148
  • 11
  • 85
  • 139
John
  • 23
  • 4
  • 2
    What is being created when you create a `std::shared_ptr foo;`? That, but 10 times. https://en.cppreference.com/w/cpp/memory/shared_ptr/shared_ptr – JohnFilleau Nov 23 '20 at 05:24
  • "`Foo() x(3) : {};`" - won't compile. I assume you meant `Foo() : x(3) {};`. – Jesper Juhl Jul 26 '23 at 14:34

2 Answers2

1

Constructs a shared_ptr with no managed object, i.e. empty shared_ptr. (ref)

So here's a small example to show that their default constructor stores nullptr.

#include <memory>
#include <array>
#include <iostream>

struct Foo {};

int main()
{
    std::array<std::shared_ptr<Foo>, 10> arr_;
    for (const auto &obj : arr_) {
        std::cout << obj.get() << '\n';
    }
}

Output

Program returned: 0
Program stdout
0
0
0
0
0
0
0
0
0
0

For instance, will the following code print 3?

No, it will dereference a nullptr and this is an undefined behavior (Usually, it is likely to cause a crash).

Sprite
  • 3,222
  • 1
  • 12
  • 29
  • 1
    Dereferencing a `nullptr` is [undefined behaviour](https://en.cppreference.com/w/cpp/language/ub). There's no guarantee that it will cause a crash - anything could happen - it might even print "3" or the compiler might optimize the whole thing out so the program does nothing at all. It's undefined. – Jesper Juhl Jul 26 '23 at 14:38
  • 1
    @JesperJuhl Corrected, thanks – Sprite Jul 27 '23 at 11:08
1

When I create an array of shared_ptrs to object Foo, what is actually being created?

Default constructed shared pointers will be created. Default constructed shared pointers are empty.

For instance, will the following code print 3?

There's no guarantee that it will. If you indirect through an empty shared pointer, the behaviour of the program will be undefined.

Or do I first need to use make_shared

That's a thing you can do.

and if so why?

Because if you don't create a Foo object, then you cannot access a Foo object.

H.S.
  • 11,654
  • 2
  • 15
  • 32
eerorika
  • 232,697
  • 12
  • 197
  • 326