0

I'm trying to initialize a vector of vector of shared_ptr class of size 19x19 ( _goban ).

class Goban
{
  public:
    Goban();
    ~Goban();
  private:
    vector<vector<shared_ptr<Cell>>> _goban;
};

My constructor is like that :

Goban::Goban() : _goban(18, vector<make_shared<Cell>>(18, new Cell))
{
}

I can't find the way to initialize.

I got this error :

template <class _Tp, class _Allocator /* = allocator<_Tp> */>

Any idea ?

Guillaume
  • 191
  • 10

1 Answers1

1

You specified the wrong template argument make_shared<Cell>, which should be shared_ptr<Cell>. And note that the implicit conversion from raw pointers to std::shared_ptr is prohibited. Then

Goban::Goban() : _goban(18, vector<shared_ptr<Cell>>(18, make_shared<Cell>()))
//                                 ^^^^^^^^^^^^^^^^      ^^^^^^^^^^^^^^^^^^^
{
}

With the help of deduction guide, you can even omit specifying the template argument as

Goban::Goban() : _goban(18, vector(18, make_shared<Cell>()))
{
}
songyuanyao
  • 169,198
  • 16
  • 310
  • 405
  • 1
    Note that this code is creating 18x18 `shared_ptr`s that all refer to a single `Cell` object in memory, it is not creating 18x18 separate `Cell` objects. If you need that, you will have to call `make_shared()` using loops, eg: `Goban::Goban() { _goban.resize(18); for (auto &v : _goban) { v.resize(18); for(auto &v2 : v) { v2 = make_shared(); } } }` Depending on use, it may be easier to create a 1D vector instead: `vector> _goban; ... _goban.resize(18*18); for (auto &v : _goban) { v = make_shared(); }` then use math to convert 2D indexes into 1D indexes when needed – Remy Lebeau Nov 06 '19 at 01:49