Std::shared_ptr initialization issue

My redacted .hpp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#ifndef CELL_HPP_
#define CELL_HPP_

#include <vector>
#include <memory>
class Entity;
using namespace std;

class Cell {

	shared_ptr< vector< shared_ptr<Entity> > > occupyingVehicles;
        //remaining members ommitted
};

#endif /* CELL_HPP_ */


My redacted .cpp

1
2
3
4
5
6
7
8
9
10
11
#include <memory>
#include "Cell.hpp"
#include "Entity.hpp"

using namespace std;

Cell::Cell(int row, int col) {
	occupyingVehicles(new vector< shared_ptr<Entity> >());
        //more initializations ommitted
}


Eclipse CDT complains with regard to the first line in the constructor body:

no match for call to '(std::shared_ptr<std::vector<std::shared_ptr<Entity> > >) (std::vector<std::shared_ptr<Entity> >*)'

I have initialized several shared pointers in this fashion without issue; can anyone please explain what I'm doing wrong?
Seeing as you are initializing an object from a constructor you will either want to use an initializer list or make_shared.

1
2
3
4
Cell::Cell(int row, int col) : occupyingVehicles(new vector< shared_ptr<Entity> >())
{
      // Other stuff
}


http://www.cplusplus.com/reference/memory/make_shared/
http://en.cppreference.com/w/cpp/language/initializer_list
It appears that this worked. I'm not sure why. I'm a little familiar with Java and I believe that, in Java, all the initialization goes into the constructor body. What do you usually put into the body of a C++ constructor and why did it work when I put the occupyingVehicles initialization in the initializer list and not when I put it into the body?


I'll take a look at your links. Thank you!
Last edited on
I haven't used Java in ages so I can't give you a similar idea there.

In C++ any time you use const/references/subobject members you need to define them in the initializer list. This is because even if you don't include it the compiler will initialize all objects at that point and in those cases that is the only chance to do it. With POD types (int, char, double etc) the compiler will also initialize them at that point, but it wont cause you any problems to keep them in the constructor body.

When you place the shared_ptr in the initializer list it uses the constructor as expected. However when you try and do occupyingVehicles(new vector< shared_ptr<Entity> >()); in the constructor body it calls the operator() which is not defined for shared_ptr and will cause problems.

I have skipped over a few details and there are a lot of good tutorials if you search around on google on initializer lists and when is the right time to use them. If anyone can give a better explanation here feel free!
Topic archived. No new replies allowed.