0

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.

André Puel
  • 8,741
  • 9
  • 52
  • 83
  • 2
    No, there is not, except to move it to another `std::string`. Why do you need this? Why can't you just use `c_str()`? – Benjamin Lindley Feb 07 '13 at 01:03
  • @BenjaminLindley I dont need. I was just wondering. – André Puel Feb 07 '13 at 01:20
  • @BenjaminLindley: Whenever I see stuff like this, my first thought is "C API/interop". Maybe he needs to pass a `char**` to a function that may reallocate it? – Mooing Duck Feb 07 '13 at 01:21
  • @MooingDuck: Well that certainly won't come to anything good, since `std::string` uses `std::allocator`, and a C function would use free/malloc or realloc. – Benjamin Lindley Feb 07 '13 at 01:28
  • @BenjaminLindley: Yes. I'm just saying that's the #1 cause of questions like this in my memory, is C APIs. Turns out this one is hypothetical, and not a C interop thing. – Mooing Duck Feb 07 '13 at 01:35

1 Answers1

2

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.

Community
  • 1
  • 1
Charles Salvia
  • 52,325
  • 13
  • 128
  • 140