0

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)?

4

1 回答 1

1

std::string可以从 C 风格的以空字符结尾的字符串 ( const char *) 初始化。没有办法std::string知道您是否需要const char * free()d、delete[]()d 或两者都不需要,并且如前所述,它不会。

使用智能指针自动删除动态分配的对象。其中有几种不同的,每种都专门用于特定目的。看看scoped_ptrauto_ptrshared_ptr。您的项目可能会限制您使用哪些智能指针。

在 C++ 的上下文中,没有理由将字符串保存在手动声明的 char 数组中,std::string使用起来更安全。

于 2013-08-23T20:58:11.397 回答