简体   繁体   English

如何删除函数中创建的指针和返回值

[英]How to delete a pointer created in a function and as the return value

class AAA{
}

class BBB{
public:
   AAA* doSomething(){
      return new AAA();
   }
}

I created and returned a pointer with NEW in a function in class BBB, I want to know whether I should delete it somewhere. 我在BBB类的函数中创建并返回了一个带有NEW的指针,我想知道是否应该在某处删除它。 If I should, then how can I achieve that? 如果我应该,那我怎么能实现呢? I have some experience in Java, but I am a total newbie in C++, please help me. 我有一些Java经验,但我是C ++的新手,请帮助我。

Sorry, I think I did not describe my problem well. 对不起,我想我没有很好地描述我的问题。 Suppose I have to write a function which concatenate two char[sizeA] and char[sizeB]. 假设我必须编写一个连接两个char [sizeA]和char [sizeB]的函数。 So I think I should do something like this: 所以我想我应该这样做:

char* concatenate(char* str1, char* str2, int sizeA, int sizeB){
   char* temp = new char[sizeA + sizeB - 1];
   ...
   return temp;
}

This is what I would do in Java, but I don't how to do it in C. I don't who is gonna use this returned char[] so I don't know where to write the "delect" code. 这就是我在Java中所做的,但我不知道如何在C中做到这一点。我不会使用这个返回的char []所以我不知道在哪里写“delect”代码。

You don't need a pointer, so why use a pointer? 你不需要指针,为什么要使用指针? What's wrong with 怎么了?

AAA doSomething()
{
   return AAA();
}

If you must, return a std::unique_ptr . 如果必须,返回std::unique_ptr

If you really want to use raw pointers, just delete the result. 如果您真的想使用原始指针,只需delete结果即可。

The way to delete a pointer is using delete : 删除指针的方法是使用delete

BBB b;
AAA *a = b.doSomething();

// ...

delete a;

But if you want make it safer use can use unique_ptr or shared_ptr . 但是如果你想让它更安全,可以使用unique_ptrshared_ptr

However in C++ you don't have to new a variable as a pointer. 但是在C ++中,您不必将new变量作为指针。 You can create an object and return it: 您可以创建一个对象并将其返回:

class BBB{
public:
    AAA doSomething() { 
       return AAA();
    }
};

since your background is java. 因为你的背景是java。 please read about parameter by value, by reference and by pointer. 请按值,参考和指针阅读参数。

AAA doSomething()
{
   return AAA();
}

you can create this function inside class B. 你可以在B类中创建这个功能。

If you don't know who is going to use the pointer you created, the best way is to transfer the ownership of the pointer (and thus, the responsibility to delete it) to the client of your class. 如果您不知道谁将使用您创建的指针,最好的方法是将指针的所有权(以及删除它的责任)转移到您的类的客户端。

There are several way to do so. 有几种方法可以做到这一点。 The simplest one is to use std::auto_ptr . 最简单的方法是使用std::auto_ptr This way, the code using your function will gain the pointer ownership upon using your function and the destruction of the std::auto_ptr variable on the client code side will lead to the deletion of the pointer you created. 这样,使用您的函数的代码将在使用您的函数时获得指针所有权,并且在客户端代码端销毁std::auto_ptr变量将导致删除您创建的指针。

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

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