c++ - 使用对 char 数组的隐式转换或编写显式转换方法是否明智?

标签 c++ string operator-overloading implicit-conversion

我正在为 UTF-8 字符串编写字符串类,但遇到了设计问题。

我希望我的一些方法将 const char *const Utf8String & 作为输入值。这是为了避免在用户传递 Utf8String 时计算长度和验证 UTF-8 字符串,并避免在用户传递一个 const char *

我还想重载 const char * 运算符(相当于 string::c_str()),因为它很方便。问题在于它会产生歧义。

这就是为什么 STL 字符串提供 c_str() 方法而不是重载运算符 const char * 的原因吗?

我可以在这里做什么?保留重载运算符 const char * 和我的方法的两个可能签名之一(const char *const Utf8String &),或者删除 const char * 运算符重载并保留两个可能的方法签名?

最佳答案

我建议写两个方法而不是使用 (const char*) 运算符。它可能会导致各种问题。

问题来了,返回指针的内存是怎么管理的?

可以这样写致命代码:

const char* getText() {
    YourType x = "text";
    return x;
}

在这里,你的类型被破坏了,很可能你的 char 数组也是如此。但这编译得很好而且看起来也不错。很难在您的代码中发现问题。

使用专用方法可以让您清楚地使用:

class YourType {
public:
    const char* createCharArray() const;
    const char* accessCharArray() const;
}

一种方法将分配一个新的 char 数组,而另一种方法将只创建一个内部临时 char 表示,该表示随类型本身一起销毁。

另一个问题是使用这样的构造函数:

class YourType {
public:
    YourType(const char *str);
}

实际上并不清楚这个构造函数的作用。您的类是存储指向字符串的指针,还是您的类创建了字符串的内部拷贝。这很可能会导致代码难以理解。

void printText(const YourType &text) {
}

允许这样:

printText("Text");

但也适用于此:

void foo(const char* text) {
    char *str = new char[strlen(text)+1];
    std::strcpy(str, text);
    printText(str);
}

这里我建议改用static转换方法:

class YourType {
public:
    static YourType fromCharArray(const char *str);
}

关于c++ - 使用对 char 数组的隐式转换或编写显式转换方法是否明智?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30464636/

相关文章:

c - 字符串字符处理 : How can I combine a post-processing loop into the primary loop?

c++ - 抽象运算符 +?

c++ - 将 itoa 与 TCHAR 一起使用

c++ - 如何制作包含所有数据文件的mfc项目的独立安装文件

c++ - 使用字符串流?

java - 在java中对字符串进行排序

c++ - 作为友元的运算符重载

c++ - 重载运算符 [] 以接受范围

c++ - 我如何在 VS2010 中创建 COM(C++)服务器?

c++ - 按值接受临时值和按引用接受非临时值的模板函数?