繁体   English   中英

C ++ 11 constexpr字符串实现

[英]C++11 constexpr string implementation

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

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

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

这不是很好,因为const auto s = "asdf"_string; 但是const string s = "asdf"_string; 才不是。 此外,constexpr_string的引用/指针不会转换。 继承任何一种方式都会导致不直观的“问题”,并且无法解决第一个问题。

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

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

这不仅仅是破坏的问题。

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM