mar*_*zzz 12 c++ const type-conversion char
我有这个代码按预期工作:
#define MAX_PARAM_NAME_LEN 32
const char* GetName()
{
return "Test text";
}
int main()
{
char name[MAX_PARAM_NAME_LEN];
strcpy(name, GetName());
cout << "result: " << name << endl;
}
Run Code Online (Sandbox Code Playgroud)
如果我想将结果存储到char *(因为框架中的某些函数我只是char *用作输入)而不使用strcpy(为了代码的实用性和可读性,以及学习),我该怎么办?保持const,这很好用:
const char* name;
name = GetName();
Run Code Online (Sandbox Code Playgroud)
但我还有const.
试着使用char*:
char* name;
name = GetName();
Run Code Online (Sandbox Code Playgroud)
我得到invalid conversion from 'const char*' to 'char*'.这种转换的最佳习惯是什么?
das*_*ght 15
这种转换的最佳习惯是在std::string整个代码中使用.由于您使用的框架const char*作为输入,您可以随时将c_str()调用结果传递给您std::string:
std::string GetName() {
return "Test text";
}
int main() {
std::string name = GetName();
int res = external_framework_function(name.c_str());
cout << "result: " << res << " for " << name << endl;
}
Run Code Online (Sandbox Code Playgroud)
const char*在您的代码中使用的是第二好的:
const char* name = GetName();
Run Code Online (Sandbox Code Playgroud)
既然你正在使用的框架也const char*很好.
如果需要非const指针,则无法复制字符串.您可以为您创建一个功能,但您仍然有责任释放您从中获得的副本:
char* copy(const char* orig) {
char *res = new char[strlen(orig)+1];
strcpy(res, orig);
return res;
}
...
char *name = copy(GetName());
...
delete[] name;
Run Code Online (Sandbox Code Playgroud)
return "Test text";返回指向只读字符串文字的指针.
如果你正在使用一个char*带有输入的函数,并且你有一个const char*(比如只读字符串文字),那么你应该提供从这个const char*函数开始的字符串的深层副本.
否则,如果函数尝试修改只读字符串,则会在运行时冒未定义的行为.
你现在拥有的是足够的; 假设你无法合作std::string.(如果您可以使用std::string 并且所有框架函数都需要const char*输入,那么我建议您重构代码以使用a std::string,并将c_str()该字符串类的方法输出传递给框架函数.)
最后,如果你的一些框架函数需要一个,char*那么你总是可以自己构建一个小的适配器类:
class Adapter
{
public:
Adapter(const& Adapter) = delete; /*don't try to copy me please*/
Adapter& operator=(const Adapter& ) = delete; /*don't try to copy me please*/
Adapter(const char* s) : m_s(::strdup(s))
{
}
~Adapter() /*free memory on destruction*/
{
::free(m_s); /*use free to release strdup memory*/
}
operator char*() /*implicit cast to char* */
{
return m_s;
}
private:
char* m_s;
};
Run Code Online (Sandbox Code Playgroud)
然后,对于一个功能void foo(char* c),你可以打电话,foo(Adapter("Hello"/*or any const char* */));并foo可以随心所欲地char*嵌入匿名临时!您甚至可以增强此类以将构造函数带到某个char*位置,在这种情况下,只会获取指针的浅表副本(并且析构函数不会删除内存).
| 归档时间: |
|
| 查看次数: |
9191 次 |
| 最近记录: |