I have a fairly simple question that I cannot seem to find an answer for relating to C++ std::string and how it is instantiated with new. Now, I am well aware that any pointer returned from new should be subsequently deleted to prevent memory leak. My question comes from what happens when an existing pointer is subsequently used to instantiate a new string object. Please consider the following simplified example:

char* foo() {
    char* ptr;

    ptr = new char[ARBITRARY_VALUE];
    ...
    ptr = strncpy("some null terminated string", ARBITRARY_VALUE)
    ...
    return ptr;
}

int main() {

    char* buf;
    std::string myStr;

    buf = foo();
    myStr = new std::string(buf);

    ...do stuff

    delete myStr;
    delete buf;         //Is this necessary?
    return 0;
}

My question is simple: does deleting myStr also free the underlying memory used by buf or does buf need to be freed manually as well? If buf has to be freed manually, what happens in the case of anonymous parameters? As in:

myStr = new std::string(foo());

My suspicion is that the underlying implementation of std::string only maintains a pointer to the character buffer and, upon destruction, frees that pointer but I am not certain and my C++ is rusty at best.

Bonus question: How would this change if the class in question were something other than std::string? I assume that for any user created class, an explicit destructor must be provided by the implementer but what about the various other standard classes? Is it safe to assume that deletion of the parent object will always be sufficient to fully destruct an object (I try to pick my words carefully here; I know there are cases where it is desirable to not free the memory pointed to by an object, but that is beyond the scope of this question)?

有帮助吗?

解决方案

std::string may be initialized from a C style null-terminated string (const char *). There is no way for std::string to know if you need that const char * free()d, delete[]()d or neither, and as already stated it won't.

Use smart-pointers to automatically delete dynamically allocated objects. There are a few different of these, each specialized for particular purposes. Have a look at scoped_ptr, auto_ptr and shared_ptr. Your project will probably have constraints on which smart pointers you get to use.

In the context of C++ there is never a reason to hold strings in manually declared char arrays, std::string is much safer to use.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top