C++ 11 constexpr字符串实现

Rob*_*son 6 c++ constexpr c++11

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

AFAIK用于构造constexpr的类需要有一个简单的析构函数.然而,当我们处理字符串时,这证明是困难的.如果字符串不是constexpr,那么它需要释放内存.但是,如果它是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); }
    }
};
Run Code Online (Sandbox Code Playgroud)

我能得到的最接近的是两个单独的类型,string和constexpr_string,用户定义的文字_string返回constexpr_string,以及用户定义的从constexpr_string到string的隐式转换.

这不是很好,虽然有效,const auto s = "asdf"_string;const string s = "asdf"_string;没有.此外,constexpr_string的引用/指针不会转换.继承任何一种方式都会导致不直观的"问题",并且无法解决第一个问题.

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

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

Mat*_* M. 10

这不仅仅是破坏的问题.

一个constexpr操作只能调用其他constexpr操作和new,malloc等等......都没有 constexpr.请注意,这是一个静态检查的属性,并且不依赖于运行时参数,因此必须完全不存在对此函数的调用,而不仅仅是隐藏在(假设)未采用的分支中.

因此,永远不可能得到一个constexpr string.

  • "你完全可以创建一个constexpr字符串类型,它只是无法处理非constexpr字符串." 这根本不是真的.非拥有运行时字符串类是完全可行的.阿卡'stringref. (3认同)