繁体   English   中英

如何释放正在返回的变量所占用的内存(使用C ++,在类中,使用析构函数)?

[英]How do I free the memory occupied by variable that is being returned (using C++, in a class, destructor)?

示例代码:

class Myclass
{
    char * function(const char *x, const char *y)
    {
        char *a, *b, *c;
        *a = strdup(x);
        *b = strdup(y);
        *c = (char *) malloc(strlen(a) + strlen(b) + 1);
        ...
        ...
        free(a);
        free(b);
        return c;
    }
};

如何free c占用的内存? 当我尝试在析构函数中执行此操作时,它表示use of undeclared identifier c 无论如何,有没有释放内存而不在构造函数中分配内存的情况?

class destructor仅应负责释放constructors for that class分配的内存。 那就是所有权。

同样,代码中的cfunction本地function因此它将不再存在于该函数之外,也就是说,肯定会发生内存泄漏,除非您从该function返回c并确保调用者对该内存调用了delete/free 但这给usability部门带来了很多负担。

回答:停!

并记住您在用c ++编写代码时,正确的做法是将内存管理留给标准库并返回值而不是指针。

class Myclass
{
    std::string function(const char *x, const char *y)
    {
        // no more overhead than strdup - and much safer!
        std::string a(x), b(y);

        // what I shall return
        std::string c;

        // un-necessary, but can improve efficiency
        c.reserve(a.size() + b.size());

        // perform my complex string algorithm
        //... for example, concatenate into c:
        c = a + b;

        // return my result    
        return c;
    }
};

现在这样调用:

{
  MyClass x;
  auto s = x.function("hello", "world");

  // s is a std::string. if I *really* want a pointer, I can...
  const char* p = s.c_str();

  // note: no need to free *anything*
}

您不能拨打free(c);电话free(c); 在析构函数中,除非c是成员变量,这是编译器告诉您的。

在这种情况下,您必须确保MyClass::function调用者在返回的值上可以free调用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM