André Puel
André Puel

Reputation: 9179

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.

Upvotes: 0

Views: 208

Answers (1)

Charles Salvia
Charles Salvia

Reputation: 53289

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.

Upvotes: 2

Related Questions