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 ?

1 Answer 1

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>()))
{
}
Sign up to request clarification or add additional context in comments.

1 Comment

Note that this code is creating 18x18 shared_ptrs 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<Cell>(); } } } Depending on use, it may be easier to create a 1D vector instead: vector<shared_ptr<Cell>> _goban; ... _goban.resize(18*18); for (auto &v : _goban) { v = make_shared<Cell>(); } then use math to convert 2D indexes into 1D indexes when needed

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.