How to Delete a Non-New Object

Is it possible to delete a non-new object?

Yes, there will be adverse effects.

You must not delete an object that was not allocated with new. If the object was allocated on the stack, your compiler has already generated a call to its destructor at the end of its scope. This means you will call the destructor twice, with potentially very bad effects.

Besides calling the destructor twice, you will also attempt to deallocate a memory block that was never allocated. The new operator presumably puts the objects on the heap; delete expects to find the object in the same region the new operator puts them. However, your object that was not allocated with new lives on the stack. This will very probably crash your program (if it does not already crash after calling the destructor a second time).

You'll also get in deep trouble if your Object on the heap lives longer than your Object on the stack: you'll get a dangling reference to somewhere on the stack, and you'll get incorrect results/crash the next time you access it.

The general rule I see is that stuff that live on the stack can reference stuff that lives on the heap, but stuff on the heap should not reference stuff on the stack because of the very high chances that they'll outlive stack objects. And pointers to both should not be mixed together.

Deleting an object in C++

Isn't this the normal way to free the memory associated with an object?

This is a common way of managing dynamically allocated memory, but it's not a good way to do so. This sort of code is brittle because it is not exception-safe: if an exception is thrown between when you create the object and when you delete it, you will leak that object.

It is far better to use a smart pointer container, which you can use to get scope-bound resource management (it's more commonly called resource acquisition is initialization, or RAII).

As an example of automatic resource management:

void test()
{
std::auto_ptr<Object1> obj1(new Object1);

} // The object is automatically deleted when the scope ends.

Depending on your use case, auto_ptr might not provide the semantics you need. In that case, you can consider using shared_ptr.

As for why your program crashes when you delete the object, you have not given sufficient code for anyone to be able to answer that question with any certainty.

How to delete an object in JavaScript?

The only way to delete an object is to remove all references for it.

The object created by your call to setBackgroundColor is deleted almost immediately because you never keep a reference to it.

If you were to uncomment the line starting \\ var newObjet then it would still be deleted almost immediately because the function would finish and the variable would drop out of scope.


I think that what you want to do is to remove the background colour setting your did.

That isn't part of the object. The function that did it was just attached to the object, but the change was to the element you passed in, not to the object itself.

If you want to change the background colour to something else then you need to do so explicitly.

else {
document.querySelector('.my_container').style.backgroundColor = "";

That said, if you want to change the style of something based on the window size, use the media query feature built into CSS.

It is a lot less hassle than searching the DOM and modifying the style with JS.

C++ delete an object

Edit: Using some sort of smart pointer is often a good idea, but I believe it is still essential to have a solid understanding of manual memory management in C++.

If you want an object in a class to persist until the end of the program, you can simply make it a member variable. From what you've said, there's nothing to suggest you need to use new or delete here, just make it an automatic variable. If you did want to use new and delete for practice, you should read up on constructors and destructors for a class (you can and will use new and delete outside of classes, but I'm trying to keep this relevant to your question). Here's one I prepared earlier:

class Foo
{
public:
Foo(); // Default constructor.
~Foo(); // Destructor.

private:
int *member;
}

Foo::Foo() // Default constructor definition.
{
member = new int; // Creating a new int on the heap.
}

Foo::~Foo() // Destructor.
{
delete member; // Free up the memory that was allocated in the constructor.
}

This is a simple example, but it will hopefully help you out. Note that the variable will only persist as long as the object is alive. If the object is destroyed or goes out of scope, the destructor will be called and the memory will be freed.

Deleting an object

delete implicitly calls the destructor, you don't need (more precisely: shouldn't) call it directly.

A destructor will never release the memory occupied by the object (It may reside on the stack, not on the heap, and the object has no way of knowing -- however, the destructor will delete any memory allocated by the object's components).

In order to free the memory of an object allocated on the heap, you must call delete.

When you write your own class, C++ will provide a default destructor to free the memory allocated by component objects (such as a QString that is a member of your class), but if you explicitly allocate memory (or other resources) in your constructor, be sure to provide a destructor that will explicitly free these resources.

Another general rule regarding your own classes: If you mark any methods virtual, your destructor should be virtual, as well (even if you rely on the default destructor), so that the correct destructor is called for any classes derived from yours.

Deleting an uninitialised object in C++

delete NULL; is guaranteed to be a no-op, so a manual check is not necessary. However, an unitialized pointer variable is not NULL, so you must explicitly set it to NULL if the condition fails:

if (strcmp(configModel, "cyclic") == 0)
fm_req_set_odom_px = new CyclicFaultModel<double>();
else
fm_req_set_odom_px = NULL;

Alternatively, you can set the pointer variable to NULL unconditionally before the if statement:

fm_req_set_odom_px = NULL;
if (strcmp(configModel, "cyclic") == 0)
fm_req_set_odom_px = new CyclicFaultModel<double>();

C++ deleting an object

you need to delete the dynamically allocated subobjects in the destructor of the main object and you have properly done this by deleting array Equipment

How do I remove a property from a JavaScript object?

To remove a property from an object (mutating the object), you can do it like this:

delete myObject.regex;
// or,
delete myObject['regex'];
// or,
var prop = "regex";
delete myObject[prop];

Demo

var myObject = {
"ircEvent": "PRIVMSG",
"method": "newURI",
"regex": "^http://.*"
};
delete myObject.regex;

console.log(myObject);

Deleting objects in C++ explicitly

You don't have to delete them explicitly, because as you have created them myclass obj; they are created on stack and deleted after each iteration.

When the program reaches the first curly brace after the instantiation on stack of an object it deletes it, in your case:

myclass obj;
obj.do_function();
} // Here the obj is deleted

Here are some examples and explanations of how stack is working, versus heap, to let you understand better when you need to free memory yourself, and when you don't.

Note: I have used notions of stack and heap only to suggest how objects are handled relatively to their lifetime like when an object from stack should be freed after it leaves the scope, and an object of heap lives until it's explicitly freed. As mentioned in comments, these notions are not considered in standard C++ because the programs can run in an environment which does not support these type of memory. Although the compiler respects these rules for a C++ program.

Core Data: How to delete objects that are not in new data

Assuming that

  • your Core Data entity has an attribute "unique_id" that uniquely identifies each
    object, and
  • the server response is stored as an array of dictionaries (e.g. from a JSON response)
    where each dictionary also contains the "unique_id",

then you can do the following: First, create an array of all unique ids from the
new objects from the server:

NSArray *uniqueIds = [serverResponse valueForKey:@"unique_id"];

Then fetch all objects with ids that are not in this array. This can be
done with a single fetch request:

NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"YourEntity"];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"NOT unique_id IN %@", uniqueIds];
request.predicate = predicate;
NSError *error;
NSArray *outdatedObjects = [context executeFetchRequest:request error:&error];
if (outdatedObjects == nil) {
// handle error ...
}

Finally, delete the outdated objects:

for (YourEntity *obj in outdatedObjects) {
[context deleteObject:obj];
}
if (![context save:&error]) {
// handle error ...
}


Related Topics



Leave a reply



Submit