哪个字符串类在c++中使用高性能和简单

which string class to use in high performance and to be simple in c++

本文关键字:高性能 简单 c++ 字符串      更新时间:2023-10-16

我正在用c++构建一个简单的框架,我听说std::string类在关键性能情况下不好,我知道在c++11中由右值引用的move构造函数修复的返回时复制问题。

  • C++11解决了这些问题吗??如果是,那么为什么有string_ref的提议http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3334.html

  • 是否建议使用std::string而不是任何其他字符串?

  • 同样,那些习惯于处理C#的用户使用std::string的简单性是非常困难的,我决定为我的字符串提供类似于.NET中System::string中的方法(我的意思是相同的名称,相同的场景,因为我知道std和STL提供了我需要的所有功能)如果字符串的性能很好,那么将其封装在一个提供所需功能的自定义类中的想法有多糟糕?如下所示:

//this is a simple scratch for what I meant by wrapping std::string inside a custom string
class CustomString
{
public:
    CustomString()// : str(nullptr) //shared_ptr will initialize to zero
    {
    }
    CustomString(const char* str)
    {
        str = make_shared<std::string>(str);
    }
    uint32_t IndexOf(char c)
    {
        //call the appropriate methods in the str->find(...
    }
    uint32_t IndexOf(const char* ofStr)
    {
        //call the appropriate methods in the str->find(...
    }
    uint32_t IndexOf(const CustomString& ofStr)
    {
        //call the appropriate methods in the str->find(...
    }
    CustomString SubString(uint32_t start = 0, uint32_t length = -1)
    {
        //call the appropriate methods in the str->substr(...
    }
    CustomString LastIndexOf(const CustonString& str)
    {
        //call the appropriate methods in the str->rfind(...
    }
    //............
    //.......
    //..complete all other needed functionality
    //.does the added in-between method call will have a noticeable  effect on the performance 
private:
    shared_ptr<std::string> str;
};

回答您的一个问题:

是否建议使用std::string而不是任何其他字符串?

是的。如果其他人想使用你的框架,那么如果你使用std::string,他们就不必担心学习使用新的字符串类。在大多数情况下,std::string的性能是令人满意的。

编辑:

当您不想使用std::string时,是指您想传递一个字符串让其他代码查看,但不想触摸。注意,与.NET中的字符串不同,c++中的字符串是可变的。因此,在c++中,按值传递std::string s的代价要高得多(因为有副本),所以您希望使用const std::string&

另一种不想使用std::string的情况是,当您想编写一个采用字符串文字的函数时(即,您需要一个可以查看但不能编辑的硬编码字符串)。为此,您需要使用const char *。这是你所能达到的效率。此外,另一个c++编程人员在查看您的代码并看到const char *时,会立即想到"字符串文字",这使代码更易于解释。