Pregunta

so i have a flyweight of strings type:

typedef boost::flyweight< std::string, boost::flyweights::intermodule_holder > SymbolName_t;

and i want to push a instance of this into a vector of them, but the naive approach won't work:

void PushSome( std::vector < SymbolName_t >& list)
{
  std::string& str = getSomeStr();
  list.push_back( str ); // <--- won't compile
}

so i added a temporary constructor:

void PushSome( std::vector < SymbolName_t >& list)
{
  std::string& str = getSomeStr();
  list.push_back( SymbolName_t(str) ); // <--- compiles ok
}

my question is: is this approach optimal, given the constraints of the language? what benefits would provide implementing this in some other way, say, by providing a static conversion operator? I don't consider a implicit conversion via a non-explicit constructor a valid option because that would require modifying the boost::flyweight template

¿Fue útil?

Solución

If you have a C++11 compiler, you can use emplace_back instead of push_back, which eliminates the need for the copy.

Otros consejos

From what I know of C++, your above code may be your best option, as you are passing a reference to the list (no assignment or copy constructor invoked), obtaining a reference to your string (again, no assignment or copy constructor), and then pushing a freshly constructed SymbolName_t onto your list. Unfortunately, STL containers operate on copies of their arguments, so a copy constructor or assignment operator (I can't remember which one the std::list uses here) would be invoked at that point. Other options might include having a conversion operator, but the list will still have to construct the initial object, and then copy it to the STL container. Even with a different STL container, this would still be true. So the conversion operator wouldn't really buy you anything, IMHO.

Your above code (the "compiles ok" block) may be your best bet. Within the constraints of STL containers, I can't think of a more efficient method. You could perhaps buy some performance by using a shared_ptr to SymbolName_t, but as boost:flyweight is already supposed to be optimized as far as managing memory, I'm not sure how much that buys you, if there are a lot of repeated strings.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top