Which string classes to use in C++?

后端 未结 7 2139
遇见更好的自我
遇见更好的自我 2021-02-02 14:30

we have a multi-threaded desktop application in C++ (MFC). Currently developers use either CString or std::string, probably depending on their mood. So we\'d like to choose a s

7条回答
  •  清酒与你
    2021-02-02 14:37

    I don't know of any other common string implementations- they all suffer from the same language limitations in C++03. Either they offer something specific, like how the ICU components are great for Unicode, they're really old like CString is, or std::string trumps them.

    However, you can use the same technique that the MSVC9 SP1 STL uses- that is, "swaptimization", which is the most hilariously named optimization ever.

    void func(std::string& ref) {
        std::string retval;
        // ...
        std::swap(ref, retval); // No copying done here.
    }
    

    If you rolled a custom string class that didn't allocate anything in it's default constructor (or checked your STL implementation), then swaptimizing it would guarantee no redundant allocations. For example, my MSVC STL uses SSO and doesn't allocate any heap memory by default, so by swaptimizing the above, I get no redundant allocations.

    You could improve performance substantially too by just not using expensive heap allocation. There are allocators designed for temporary allocations, and you can replace the allocator used in your favourite STL implementation with a custom one. You can get things like object pools from Boost or roll a memory arena. You can get tenfold better performance compared to a normal new allocation.

提交回复
热议问题