Search code examples
c++raii

Understanding RAII object


I'm reading about RAII principle and have some questions about it. In fact, it encapsulates the resource. So, consider the class std::string. It has a constructor string (const char* s);. So, like smart pointers (e.g. template explicit shared_ptr (U* p);) it takes a pointer to the resource and then manages it. Is it correct to say so about strings?


Solution

  • like smart pointers (e.g. shared_ptr) it takes a pointer to the resource and then manages it. Is it correct

    Not quite. shared_ptrs take part in ownership of the object to which that pointer points, while unique_ptr takes exclusive ownership. Of smart pointers, weak_ptr doesn't take ownership immediately, but it does join as an observer of an object owned by shared_ptrs and allows sharing of ownership to be attempted later.

    The point is that those smart pointers take ownership of an existing object indicated by the pointer they're given.

    std::string(const char*), on the other hand, makes a copy of the NUL-terminated string to which the pointer points, which it then has exclusive ownership of. The original text to which the constructor's pointer argument pointed is of no on-going relevance to the string object constructed; for example, modifications to the string do not affect that text. Separately, the std::string object may internally keep a pointer to a dynamically allocated buffer storing the copy of the text, and that buffer can be resized and updated (other times - for sufficiently short text - it may be stored directly in the std::string object as an optimisation). On destruction, std::string will delete[] any internal pointer it is still managing. They never leak memory.