简体   繁体   中英

Extract const char from std::string without copying?

I was wondering if there is some way to tell the std::string to release the char* it is using.

I imagine that somewhere on the std::string it has a field of type char* , I was wanting some method that would to something like that:

const char* std::string::release() {
    const char* result = __str;
    __size = 0;
    __capacity = INITIAL_CAPACITY_WHATEVER;
    __str = new char[INITIAL_CAPACITY_WHATEVER];
    return result;
}

Not that copying the content is a problem or will affect my performance, I just was felling uncomfortable with wasting time copying something that I am just going to delete after.

If you're using C++11, you can use std::move to move the contents of one string object to another string object. This avoids the overhead of copying.

std::string s1 = "hello";
std::string s2(std::move(s1));

However, you cannot directly disassociate the internal char* buffer from an instance of std::string . The std::string object owns the internal char* buffer, and will attempt to deallocate it when the destructor is invoked.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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