C ++字符串类,提供`slice`操作(不创建新的字符串副本)

时间:2014-04-11 01:23:45

标签: c++ string slice

是否存在提供切片操作的现有C ++字符串类,并且没有创建新的字符串副本? (有点像go编程语言中的string

awesome::CString s = "this is an awesome string";
awesome::CString s1 = s.Mid(8, 10); // contains "an awesome" but not new copy
if (s1 == "an awesome") {
    awesome::CString s2 = s.Mid(11); // contains " string"
}
std::string str = s.str(); // create a copy that is the usual string

我认为go的实现对于解析字符串数据更有效(例如解析APDU

2 个答案:

答案 0 :(得分:1)

尽管如此,我相信存储引用的类可能是最好的解决方案。

这并不完全符合您的要求,因为仍然会生成临时副本以提供子字符串。但结果是预期的,我认为它在安全性和可读性之间取得平衡,而不是使用黑客等,因为STL明确表示不对底层字符串存储做出假设。

#include <iostream>
#include <cstring>

using namespace std;

class stringRef {
   public:
    string & src;
        size_t i;
        size_t s;
        stringRef(string &ssrc, size_t i_pos, size_t i_spam):src(ssrc){
            i=i_pos;
            s=i_spam;
        }
        operator const string(){
        return string(src.substr(i, s));
        }
    };

int main() {
    string s("this is an awesome string");
    stringRef s1(s, 8, 10);       //initializes [s1] bound to [s]
    cout << (string)s1 << endl;   //prints [s1]
    s=" quite a cool workaround"; //modifies [s]
    cout << (string)s1 << endl;   //prints [s1]
    return 0;
}

将输出:

an awesome
 cool work

从那以后你就可以改善课程,做任何你想做的事情=)

答案 1 :(得分:0)

class AwesomeString {
private:    
    struct AwesomeData {
        std::string str;
        size_t refcnt;

        AwesomeData( const char *that ) {
            str = std::string(that);
            refcnt = 1;
        }
    };

    AwesomeData *data;
    size_t from, to;

public:
    AwesomeString( const char *str ) {
        data = new AwesomeData(str);
        from = 0;
        to = data->str.length();
    }

    AwesomeString( const AwesomeString &other, size_t begin, size_t end) {
        // Here is where the interesting part begins:
        data = other.data; // reference the same data
        data->refcnt++; // increment reference count
        from = begin;
        to = end;
    }

    ~AwesomeString() {
        data->refcnt--; // decrement reference count
        if(refcnt == 0) {
            // delete data on deletion of the last object that references it
            delete data; 
        }
    }

    operator const string() {
        return data->str.substr(from, to);
    }
};

我试图在这里指出指针/引用指向具有良好控制生命周期的对象:保证AwesomeData的指针数据永远不会指向已删除的对象。