C++11 constexpr 字符串实现

C++11 constexpr string implementation

本文关键字:实现 字符串 constexpr C++11      更新时间:2023-10-16

有没有办法实现字符串在编译时和运行时工作?

AFAIK 对于要构造的类,它需要有一个简单的析构函数。 但是,当我们处理字符串时,这被证明是困难的。 如果字符串不是 constexpr,那么它需要释放内存。 但是,如果它是 constexpr,那么它是静态分配的,不应该被删除,从而允许一个微不足道的析构函数。

但是,不可能说"嘿,编译器! 如果我是魔术师,你不需要毁掉我!还是吗?

它将如下所示:

class string {
private:
    char * str;
public:
    template<std::size_t l>
    constexpr string(const char (&s)[l]) : str(&(s[0])) {}
    string(const char * s) { str = strdup(s); }
    static if (object_is_constexpr) {
        ~string() = default;
    }
    else {
        ~string() { free(str); }
    }
};

我能够得到的最接近的是有两种单独的类型,字符串和constexpr_string,用户定义的文字_string返回constexpr_string,以及用户定义的从constexpr_string到字符串的隐式转换。

不过这不是很好,因为const auto s = "asdf"_string;有效,但const string s = "asdf"_string;不起作用。 此外,指向constexpr_string的引用/指针不会转换。 无论哪种方式,继承都会导致不直观的"陷阱",并且不能解决第一个问题。

这似乎是可能的,只要编译器信任程序员不需要破坏 constexpr。

如果我有误解,请告诉我。

这不仅仅是一个破坏的问题。

一个constexpr操作应该只调用其他constexpr操作,newmalloc等都不constexpr请注意,这是一个静态检查的属性,不依赖于运行时参数,因此必须完全不存在对此类函数的调用,而不仅仅是隐藏在(据说(未采用的分支中。

因此,永远不可能获得constexpr string.

在某种程度上,可以查看本页中的代码示例。您可以创建 constexpr conststr对象并对其调用一些操作,但不能将它们用作非类型模板参数。