c++11 - Instantiate an object separately for shared pointer C++ -


the below code works fine:

std::map<std::string,std::ofstream*> m_jstabfilesmap; m_jstabfilesmap.insert({ listoftabnames[i], new std::ofstream(jsfilename)}); 

but if replace normal pointer shared pointer insert function complaints no overloaded version of function insert() exists.

std::map<std::string, std::shared_ptr<std::ofstream>> m_jstabfilesmap; 

how fix ? has way i'm instantiating object using new.

the constructor of std::shared_ptr<t> takes t* explicit, , reason. implicitly creating owning smart pointer when raw pointer passed in asking trouble.

this means must change way insert function. remain exception-safe, raw pointer -> smart pointer conversions should happen 1 @ time, or through functions. in case, it's best use std::make_shared:

std::map<std::string, std::shared_ptr<std::ofstream>> m_jstabfilesmap; m_jstabfilesmap.insert({ listoftabnames[i], std::make_shared<std::ofstream>(jsfilename)}); 

Comments

Popular posts from this blog

Is there a better way to structure post methods in Class Based Views -

Python Tornado package error when running server -

Qt QGraphicsScene is not accessable from QGraphicsView (on Qt 5.6.1) -