I’m trying to initialize a shared_ptr with a map that has optional values. I’ll initialize the values in a later stage of my program.
I read the following post and used it as a guide: How to add valid key without specifying value to a std::map?
But my situation is a little bit different because I’m using a shared_ptr. Without further ado, this is the code I wrote:
ShaderProgram.h
...
#include <map>
#include <boost/shared_ptr.hpp>
#include <boost/optional.hpp>
typedef map<string, optional<GLuint> > attributes_map;
class ShaderProgram
{
public:
ShaderProgram(vector<string> attributeList);
...
private:
shared_ptr<attributes_map> attributes;
};
ShaderProgram.mm
ShaderProgram::ShaderProgram(vector<string> attributeList)
{
// Prepare a map for the attributes
for (vector<string>::size_type i = 0; i < attributeList.size(); i++)
{
string attribute = attributeList[i];
attributes[attribute];
}
}
The compiler notifies me about the following error: Type ‘shared_ptr’ does not provide a subscript operator.
Anyone an idea what might be the problem?
attributesis ashared_ptrand does not haveoperator[]but amapdoes. You need to dereference it:Note no
mapobject has been allocated forattributesin the constructor so once the compiler error is resolved you will get a runtime failure of some description. Either allocate amapinstance:or don’t use a
shared_ptr, as it is not obvious why dynamic allocation is required in this case:Pass the
attributeListby a reference to avoid unnecessary copying and asconstas the constructor does not modify it: