I am refactoring an old C library, and am currently changing the external API so that it uses std::string instead of const char*.
ColumnType Table::getColType(const char *name) const
{
int id = getColumnId(name) ;
return getColType(id) ;
}
and
int Table::getColumnId (const char * col_name) const
{
unsigned int i = 0;
while ((i < m_table.num_cols) && (strcmp(m_table.cols[i]->name, col_name) != 0) )
i++;
if (i < m_table.num_cols)
return i;
else
return -1;
}
To:
ColumnType Table::getColType(const std::string& name_in) const
{
const char* name = name_in.c_str();
int id = getColumnId(name) ;
return getColType(id) ;
}
and
int Table::getColumnId (const std::string& col_name_in) const
{
const char* col_name = col_name_in.c_str();
unsigned int i = 0;
while ((i < m_table.num_cols) && (strcmp(m_table.cols[i]->name, col_name) != 0) )
i++;
if (i < m_table.num_cols)
return i;
else
return -1;
}
In the new code, I am passing a const char* to functions that are now expecting a reference to const std::string. I know std::string can be initialised from a const char*, and the code compiles correctly (no warnings etc).
But I just want to make sure that I am not doing anything that will come to bite me later on (I18n issues aside).
In short - is what am doing "safe"?
const char*, and not thestringitself? The only thing I can think of is that there will be unnecessary copies with each call... - NimgetColumnIdwhich accepts astd::stringis passed aconst char*- a bit redundant really... - Nimconst char*and then ignore them? That forces unneeded copies. - Mooing Duck