Search code examples
c++classc++11sharedstdmap

Can't set values in an std::map<std::string,std::shared_ptr<class>>


I'm trying to make a map as showed in the title of this post to link certain bass classes to MQTT topic titles.

I've got I working with raw (c style) pointers, but as I've learned in school smart pointers would be a better design option.

The problem doesn't occur when instantiating the map, but when I want to assign data to it.

The way I've got it working perfectly is:

std::map<std::string,sensors*> factory;
factory["sensorTwo"]= new sensor1;

In this code "sensors" is the baseclass of sensor1;

When I try to do it like this:

std::map<std::string,std::shared_ptr<sensors>> factory;
factory["sensorOne"]= std::make_shared<sensors> (sensor1);

The compiler asks for a primary expression before ';' on the second line. The assignment in the first example obviously doesn't work with the shared_ptr, but does anybody have an idea on how to do this?

main looks as follows:

#include <string>
#include <memory>
#include <map>

#include "sensors.h"
#include "sensor1.h"
#include "sensor2.h"


int main()
{
    //std::map<std::string,sensors*> factory;

    std::map<std::string,std::shared_ptr<sensors>> factory;
    factory["sensorOne"]= std::make_shared<sensor1> ();
    return 0;
}

Solution

  • Given you have declared structures Foo and Bar as follows:

    struct Foo {};
    struct Bar : Foo {};
    

    Correct syntax for std::make_shared to make a std::shared_ptr<Foo> pointing to a Bar instance is:

    std::shared_ptr<Foo> sp = std::make_shared<Bar>();
    

    From your first example, Foo is sensors and Bar is sensor1. So your code should not be:

    factory["sensorOne"]= std::make_shared<sensors> (sensor1);
    

    But:

    factory["sensorOne"]= std::make_shared<sensor1> ();