Self delete an object in C++ [duplicate] - c++

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
C++: Delete this?
Object-Oriented Suicide or delete this;
I wonder if the code below is run safely:
#include <iostream>
using namespace std;
class A
{
public:
A() {
cout << "Constructor" << endl;
}
~A() {
cout << "Destructor" << endl;
}
void deleteMe() {
delete this;
cout << "I was deleted" << endl;
}
};
int main()
{
A *a = new A();
a->deleteMe();
cout << "Exit ...";
return 0;
}
Output is:
Constructor
Destructor
I was deleted
Exit ...
and program exit normally, but are there some memory access violents here?

It's ok to delete this in case no one will use the object after that call. And in case the object was allocated on a heap of course
For example cocos2d-x game engine does so. It uses the same memory management scheme as Objective-C and here is a method of base object:
void CCObject::release(void)
{
CCAssert(m_uReference > 0, "reference count should greater than 0");
--m_uReference;
if (m_uReference == 0)
{
delete this;
}
}
I don't think it's a c++ way of managing memory, but it's possible

It's ok, because you have running simple method. After delete this, all variables and virtual table are clear. Just, analyze this example:
#include <iostream>
class foo
{
public:
int m_var;
foo() : m_var(1)
{
}
void deleteMe()
{
std::cout << m_var << "\n";
delete this;
std::cout << m_var << "\n"; // this may be crush program, but on my machine print "trash" value, 64362346 - for example
}
virtual void bar()
{
std::cout << "virtual bar()\n";
}
void anotherSimpleMethod()
{
std::cout << "anotherSimpleMethod\n";
}
void deleteMe2()
{
bar();
delete this;
anotherSimpleMethod();
// bar(); // if you uncomment this, program was crashed, because virtual table was deleted
}
};
int main()
{
foo * p = new foo();
p->deleteMe();
p = new foo();
p->deleteMe2();
return 0;
}
I've can't explain more details because it's need some knowledge about storing class and methods in RAM after program is loaded.

Absolutelly, you just run destructor. Methods does not belongs to object, so it runs ok. In external context object (*a) will be destroyed.

When in doubt whether theres strange things going on in terms of memory usage (or similar issues) rely on the proper analysis tools to assist you in clarifying the situation.
For example use valgrind or a similar program to check whether there are memory leaks or similar problems the compiler can hardly help you with.
While every tool has its limitations, oftentimes some valuable insights can be obtained by using it.

There is no memory access violation in it, you just need to be careful. But deleting this pointer is not recommended at all in any language, even though the code above would work fine. As it is same as delete a, But try doing it other way, the safe way.
For example there is something illogical in your posted code itself.
void deleteMe()
{
delete this;
cout << "I was deleted" << endl; // The statement here doesn't make any sense as you no longer require the service of object a after the delete operation
}
EDIT: For Sjoerd
Doing it this way make more sense
void deleteMe()
{
delete this;
}
int main()
{
A *a = new A();
a->deleteMe();
cout << "a was deleted" << endl;
cout << "Exit ...";
return 0;
}
The second line in your deleteMe() function should never be reached, but its getting invoked. Don't you think that its against the language's philosophy?

Related

Using RAII to replace the finally block to free memory

I was studying about the RAII mechanism in C++ which replaces the finally of Java.
I wrote the following code to test it:
void foo(int* arr) {
cout << "A" << endl;
throw 20;
cout << "B" << endl;
}
class Finally {
private:
int* p;
public:
Finally(int* arr) {
cout << "constructor" << endl;
p = arr;
}
~Finally() {
cout << "destructor" << endl;
delete(p);
}
};
int main()
{
int * arr = new int[10];
new Finally(arr);
try {
foo(arr);
} catch (int e) {
cout << "Oh No!" << endl;
}
cout << "Done" << endl;
return 0;
}
I want to free the memory which I used for arr so I set a new class Finally which saves the pointer to the array and when it exits the scope it should call the destructor and free it. But the output is:
constructor
A
Oh No!
Done
No call for the destructor. It also does not work when I move the body of main to some other void method (like void foo()). What fix should I do to achieve the desired action?
That's because the object you create with new Finally(arr) doesn't really gets destructed in your program.
Your allocation of the object just throws the object away immediately, leading to a memory leak, but more importantly it's created outside the scope of the try and catch.
For it to work you have to do something like
try {
Finally f(arr);
foo(arr);
} catch (int e) {
cout << "Oh No!" << endl;
}
That would create a new object f in the try, which will then get destructed when the exception is thrown (as well as when it goes out of scope of the try if no exception is thrown).
You're assuming C++ works liked Java. It doesn't, so there are actually a few things wrong in your code
The statement
new Finally(arr);
dynamically allocates a Finally, but it is NEVER released in your code. Hence its destructor is never called.
Instead do
Finally some_name(arr);
This will invoke the destructor of Finally - at the end of main() - which will give the output your expect.
However, the second thing wrong is that the destructor of Finally does delete (p) which gives undefined behaviour, since p is the result (in main()) of new int [10]. To give the code well-defined behaviour, change delete (p) to delete [] p.
Third, with the two fixes above, you are not using RAII. RAII means "Resource Acquisition Is Initialisation", which is not actually what your code does. A better form would be to initialise p using a new expression in Finallys constructor and release it with a correct delete expression in the destructor.
class Finally
{
private:
int* p;
public:
Finally() : p(new int [10])
{
cout << "constructor" << endl;
};
~Finally()
{
cout << "destructor" << endl;
delete [] p;
};
int *data() {return p;};
};
AND replace the first two lines of your main() with a single line
Finally some_name;
and the call of foo() with
foo(some_name.data());
More generally, stop assuming that C++ works like Java. Both languages work differently. If you insist on using C++ constructors like you would in Java, you will write terribly buggy C++ code.

Null Object is calling A Method but Program is not crashing.. .How ... Why? [duplicate]

This question already has answers here:
What will happen when I call a member function on a NULL object pointer? [duplicate]
(6 answers)
Closed 4 years ago.
I was trying some code. Mistakenly wrote below code (Luckily Now)
Snippet 1
#include<iostream>
using namespace std;
class A {
public:
A() { cout << "A()" << endl; }
~A() { cout << "~A()" << endl; }
void print() { cout << "A::print()=>" <<this<< endl; }
};
int main() {
A* a = new A;
a->print();
delete a;
a = NULL;
cout << a << endl;
a->print();
return 0;
}
As I know, since I have deleted "a", the program should have crashed (Not so true now). But it did not. Can some please explain the reason behind this. The output image is also attached.
But As soon as I include any member variable in the above program, it crashes.
How ? Why ? Please see Program 2.
Snippet 2
class A {
int val;
public:
A() { cout << "A()" << endl; }
~A() { cout << "~A()" << endl; }
void print() { cout << "A::print()=>" <<this << val << endl; }
};
int main() {
A* a = new A;
a->print();
delete a;
a = NULL;
cout << a << endl;
a->print();
return 0;
}
The Above program is crashing. Why not the 1st program?
PS: There are chances that it may be the duplicate question. I tried to find the question like this but couldn't find. Though I got this question, I feel it's not the same as I am looking for.
The first one doesn’t dereference any memory pointed by anything, therefore it might not crash. You’re only printing out this which is a pointer value and you’re not dereferencing it. Note that this doesn’t mean it’s ok and will always work! It is definitely not allowed and shouldn’t be done. What happens when this is done is undefined.
Your second example actually tries to use a member variable which means an attempt is made to access memory that isn’t valid. This is also undefined behavior and may cause a crash, or something else. It is undefined.

Why doesn't this dangling std::weak_ptr cause SEGFAULT? [duplicate]

This question already has answers here:
When does invoking a member function on a null instance result in undefined behavior?
(2 answers)
Closed 4 years ago.
In the following code I create a shared_ptr in the scope and assign it to a weak_ptr. How come when running the code I don't get SEGFAULT, because wp should be invalid out of scope, right?
namespace {
struct Dummy {
int x;
void foo() {
std::cout << "dummy created\n";
}
~Dummy()
{
std::cout << "dummy destroyed\n";
}
};
}
TEST(experimental, ptr_test){
std::weak_ptr<Dummy> wp;
{
auto sp = std::make_shared<Dummy>();
wp = sp;
}
wp.lock()->foo();
};
You're not actually dereferencing anything there though. The lock method will still return a shared_ptr if the locked shared_ptr is null, but that shared_ptr will also be null. In this example, foo doesn't crash on my compiler since it never dereferences the null pointer but it's undefined behavior so you never know what will happen. However, bar will always crash since it needs to dereference the pointer in order to get to x.
The reason why this happens to work is that all member functions compile to normal functions that take a pointer to the object as their first parameter accessible from the function body as this. Calling this function on nullptr will probably work most of the time if nothing in the body of the function dereferences this. You shouldn't do it though, future compiler changes or a port to another architecture could cause this to crash.
#include <iostream>
#include <memory>
struct Dummy {
int x;
Dummy()
: x(10) {
std::cout << "Dummy created" << std::endl;
}
~Dummy() {
std::cout << "Dummy destroyed" << std::endl;
}
void foo() {
std::cout << "foo" << std::endl;
}
void bar() {
std::cout << x << std::endl;
}
};
int main() {
std::weak_ptr<Dummy> wp;
{
auto sp = std::make_shared<Dummy>();
wp = sp;
}
auto locked = wp.lock();
if(locked.get() == nullptr) {
std::cout << "Locked pointer is null" << std::endl;
}
locked->foo(); // Does not crash
((Dummy*)nullptr)->foo(); // Does not crash
locked->bar(); // Will crash
}
Generally, you won't get a segfault unless you actually do something with the invalid memory (and then it won't always segfault - it is up to the hardware to send a signal to the OS, and then up to the OS to actually crash the program). If you were to set x in foo, you may have a better chance of seeing a segfault - but as user2357112 pointed out, the c++ standard does not guarantee a segfault for invalid code.

Delete inside of class

I got some weird problem. I use delete operator inside of class method and I want to know how solve this problem.
This is code:
#include <iostream>
using namespace std;
class A
{
public:
int a;
~A() {
cout << "call ~A()" << endl;
}
void action()
{
/* code here */
delete this; //this line depends on some if statements
/* code here */
}
void test2() {
cout << "call test2()" << a << endl;
}
void test() {
a = 10;
cout << "call test()" << endl;
action();
//how can I check if data is deleted?
test2();
}
};
int main()
{
A* a = new A();
a->test();
}
How can I check if data is deleted by delete operator?
Is it even possible?
Using delete this; is nearly always "bad". There are exceptions, but those are really unusual. Think about what you are trying to do. Most of the time, this means that you should have a wrapper object and an inner object that is created/deleted by the wrapper object.
You can't check if something has been deleted (in a reliable way/portable way). In your particular test-case, you are exercising "undefined behaviour" by "using an object after it has been destroyed", which means you can't really tell what is going to happen. You have to trust the C++ runtime that delete does what it says on the label.
In C++ there are other return values available than void. Therefore your action can return something that indicates if this has been deleted or not.
Note that you should not access any non-static data members or call any non-static member functions after deleteing this. Some people feel it to be difficult to guarantee so they ban delete this altogether.
Note to opponents that C++ FAQ claims that delete this is legal construct and I haven't also found anything forbidding it.

What is the purpose of a function try block? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
When is a function try block useful?
Difference between try-catch syntax for function
This code throws an int exception while constructing the Dog object inside class UseResources. The int exception is caught by a normal try-catch block and the code outputs :
Cat()
Dog()
~Cat()
Inside handler
#include <iostream>
using namespace std;
class Cat
{
public:
Cat() { cout << "Cat()" << endl; }
~Cat() { cout << "~Cat()" << endl; }
};
class Dog
{
public:
Dog() { cout << "Dog()" << endl; throw 1; }
~Dog() { cout << "~Dog()" << endl; }
};
class UseResources
{
class Cat cat;
class Dog dog;
public:
UseResources() : cat(), dog() { cout << "UseResources()" << endl; }
~UseResources() { cout << "~UseResources()" << endl; }
};
int main()
{
try
{
UseResources ur;
}
catch( int )
{
cout << "Inside handler" << endl;
}
}
Now, if we replace the definition of the UseResources() constructor, with one that uses a function try block, as below,
UseResources() try : cat(), dog() { cout << "UseResources()" << endl; } catch(int) {}
the output is the same
Cat()
Dog()
~Cat()
Inside handler
i.e., with exactly the same final result.
What is then, the purpose of a function try block ?
Imagine if UseResources was defined like this:
class UseResources
{
class Cat *cat;
class Dog dog;
public:
UseResources() : cat(new Cat), dog() { cout << "UseResources()" << endl; }
~UseResources() { delete cat; cat = NULL; cout << "~UseResources()" << endl; }
};
If Dog::Dog() throws, then cat will leak memory. Becase UseResources's constructor never completed, the object was never fully constructed. And therefore it does not have its destructor called.
To prevent this leak, you must use a function-level try/catch block:
UseResources() try : cat(new Cat), dog() { cout << "UseResources()" << endl; } catch(...)
{
delete cat;
throw;
}
To answer your question more fully, the purpose of a function-level try/catch block in constructors is specifically to do this kind of cleanup. Function-level try/catch blocks cannot swallow exceptions (regular ones can). If they catch something, they will throw it again when they reach the end of the catch block, unless you rethrow it explicitly with throw. You can transform one type of exception into another, but you can't just swallow it and keep going like it didn't happen.
This is another reason why values and smart pointers should be used instead of naked pointers, even as class members. Because, as in your case, if you just have member values instead of pointers, you don't have to do this. It's the use of a naked pointer (or other form of resource not managed in a RAII object) that forces this kind of thing.
Note that this is pretty much the only legitimate use of function try/catch blocks.
More reasons not to use function try blocks. The above code is subtly broken. Consider this:
class Cat
{
public:
Cat() {throw "oops";}
};
So, what happens in UseResources's constructor? Well, the expression new Cat will throw, obviously. But that means that cat never got initialized. Which means that delete cat will yield undefined behavior.
You might try to correct this by using a complex lambda instead of just new Cat:
UseResources() try
: cat([]() -> Cat* try{ return new Cat;}catch(...) {return nullptr;} }())
, dog()
{ cout << "UseResources()" << endl; }
catch(...)
{
delete cat;
throw;
}
That theoretically fixes the problem, but it breaks an assumed invariant of UseResources. Namely, that UseResources::cat will at all times be a valid pointer. If that is indeed an invariant of UseResources, then this code will fail because it permits the construction of UseResources in spite of the exception.
Basically, there is no way to make this code safe unless new Cat is noexcept (either explicitly or implicitly).
By contrast, this always works:
class UseResources
{
unique_ptr<Cat> cat;
Dog dog;
public:
UseResources() : cat(new Cat), dog() { cout << "UseResources()" << endl; }
~UseResources() { cout << "~UseResources()" << endl; }
};
In short, look on a function-level try-block as a serious code smell.
Ordinary function try blocks have relatively little purpose. They're almost identical to a try block inside the body:
int f1() try {
// body
} catch (Exc const & e) {
return -1;
}
int f2() {
try {
// body
} catch (Exc const & e) {
return -1;
}
}
The only difference is that the function-try-block lives in the slightly larger function-scope, while the second construction lives in the function-body-scope -- the former scope only sees the function arguments, the latter also local variables (but this doesn't affect the two versions of try blocks).
The only interesting application comes in a constructor-try-block:
Foo() try : a(1,2), b(), c(true) { /* ... */ } catch(...) { }
This is the only way that exceptions from one of the initializers can be caught. You cannot handle the exception, since the entire object construction must still fail (hence you must exit the catch block with an exception, whether you want or not). However, it is the only way to handle exceptions from the initializer list specifically.
Is this useful? Probably not. There's essentially no difference between a constructor try block and the following, more typical "initialize-to-null-and-assign" pattern, which is itself terrible:
Foo() : p1(NULL), p2(NULL), p3(NULL) {
p1 = new Bar;
try {
p2 = new Zip;
try {
p3 = new Gulp;
} catch (...) {
delete p2;
throw;
}
} catch(...) {
delete p1;
throw;
}
}
As you can see, you have an unmaintainable, unscalable mess. A constructor-try-block would be even worse because you couldn't even tell how many of the pointers have already been assigned. So really it is only useful if you have precisely two leakable allocations. Update: Thanks to reading this question I was alerted to the fact that actually you cannot use the catch block to clean up resources at all, since referring to member objects is undefined behaviour. So [end update]
In short: It is useless.