gpt4 book ai didi

c++ - 交换 const char* 和 std::string

转载 作者:行者123 更新时间:2023-11-30 04:32:04 26 4
gpt4 key购买 nike

我正在重构一个旧的 C 库,目前正在更改外部 API,以便它使用 std::string 而不是 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;
}

收件人:

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;
}

在新代码中,我将 const char* 传递给现在需要引用 const std::string 的函数。我知道 std::string 可以从 const char* 初始化,并且代码编译正确(没有警告等)。

但我只是想确保我没有做任何以后会咬我的东西(抛开 I18n 问题)。

简而言之 - 我在做什么“安全”吗?

最佳答案

只要正确执行,它是安全的,不会造成任何伤害。

不过,除非您能指出实质性好处,否则我不建议继续进行此操作。

可能更安全的方法是添加一个接受 const string& 的函数,并直接传递给 const char* 函数。这样,您就可以让客户保留 std::string& 代码,而无需修改内部结构。

例如:

ColumnType Table::getColType(const std::string& name_in) const
{
return getColType(name_in.c_str());
}

关于c++ - 交换 const char* 和 std::string,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7909242/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com