String-for-Carrying String Conversion: Better Performance
so I have string type flies:
typedef boost::flyweight< std::string, boost::flyweights::intermodule_holder > SymbolName_t;
and I want to cast an 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 limitations of the language? What are the benefits of doing this in some other way, say by providing a static conversion operator? I am not considering implicit conversion via the implicit constructor a valid parameter, because it would require changing the templateboost::flyweight
source to share
From what I know about C ++, your above code might be your best bet, since you are passing a reference to the list (no assignment or copy constructor called), getting a reference to your string (again, no assignment or copy constructor) and then clicking the newly created one SymbolName_t
into your list. Unfortunately STL containers operate on copies of their arguments , so the copy constructor or assignment operator (I can't remember which one usesstd::list
here) will be called at this point. Other options might include a transform operation, but the list will still have to create the original object and then copy it into the STL container. Even with a different STL container, this would still be true. So the conversion operator wouldn't really buy anything IMHO.
Your above code (compilation block ok) might be your best bet. Within the constraints of STL containers, I cannot think of a more efficient method. You could buy some performance using shared_ptr
to SymbolName_t
, but since it boost:flyweight
should already be optimized for memory management, I'm not sure how much you're buying if there are a lot of duplicate lines.
source to share