Here is a sample code that I have:
void test() { Object1 *obj = new Object1(); . . . delete obj; }
I run it in Visual Studio, and it crashes at the line with 'delete obj;'. Isn't this the normal way to free the memory associated with an object? I realized that it automatically invokes the destructor... is this normal?
Here is a code snippet:
if(node->isleaf()) { vector<string> vec = node->L; vec.push_back(node->code); sort(vec.begin(), vec.end()); Mesh* msh = loadLeaves(vec, node->code); Simplification smp(msh); smp.simplifyErrorBased(errorThreshold); int meshFaceCount = msh->faces.size(); saveLeaves(vec, msh); delete msh; }
loadleaves()
is a function that reads a mesh from disk and creates a Mesh
object and returns it.(think of vec
and node->code
are just information about the file to be opened)
Should I remove the delete msh;
line?
Right-click over the objects you want to delete, and choose Delete. In the Delete dialog box, select the objects you want to delete from the list.
When delete is used to deallocate memory for a C++ class object, the object's destructor is called before the object's memory is deallocated (if the object has a destructor). If the operand to the delete operator is a modifiable l-value, its value is undefined after the object is deleted.
In C++, the single object of the class which is created at runtime using a new operator is deleted by using the delete operator, while the array of objects is deleted using the delete[] operator so that it cannot lead to a memory leak.
You cannot delete an managed object in C# . That's why is called MANAGED language. So you don't have to troble yourself with delete (just like in c++). It is true that you can set it's instance to null.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With