简体   繁体   中英

Do I have to delete the object behind a pointer before assigning a new one in C++?

Consider the following situation in C++:

void Light::setColor(Color* &color, ColorType type)
{
    color = new Color(type);
}

Do I have to delete the value that might has been stored at pointer "color" before, since C++ does not delete such objects itself? I have tried different combinations:

delete *&color;
delete &color;
delete &*color;

Nothing works.

 delete color;

将工作并学习如何拼写

If you have just this function you cannot say whether or not color was allocated beforehand. You may have a nullptr or a valid pointer in both case delete color; will work (because there is no need to test for nullptr when calling delete ).

But you may get something wrong (a non initialized pointer or even a pointer to a object allocated on the stack) and in that case delete will fail.

I would recommand that you use std::shared_ptr<Color> it will solve your ownership problems.

void Light::setColor(std::shared_ptr<Color>& color, ColorType type)
{    
    color = std::make_shared<Color>(type);
}

Or better:

std::shared_ptr<Color> Light::setColor(ColorType type)
{    
   return std::make_shared<Color>(type);
}

But by convention, a method starting with "set" is supposed to assign something to a internal member. createColor would be better.

This is a more general question regarding pointers.

When you have a pointer to an object, you are referencing a part of memory. When you delete that memory, it gets freed.

So, if you do:

color = new Color(...);

you are allocating a piece of memory with the contents of an object of type Color.

Thus, you can just delete that memory through that pointer:

delete color;

Now, in this case, *color wouldn't be too useful: you are referencing the MEMORY that the object occupies, which isn't what you want.

Let's take another example: if you have a simple object, say an array of characters:

char *str = new char[200];

then the pointer str points to the instantiated object, and *str to the memory contents that the object occupies. In that case, the pointer itself isn't what you want: you are interested in the actual data stored in that memory block (ie a string of characters).

Thus, delete[] str; will delete the memory block that str points to. delete[] *str; won't make much sense.

so, if we try this with printf():

char *str = new char[200];
strcpy(str, "test");
printf("The variable's contents are: %s", str); // will print the string itself
printf("The variable's address is: %p", str);   // will print the address of the string in memory

Here's a useful link regarding pointers, to clear some things out: http://courses.washington.edu/css342/zander/css332/pointers.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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