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.
Related
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.
#include <iostream>
using namespace std;
class BaseClass
{
public:
BaseClass(int i)
{
data = i;
cout << "_____BaseClass()____" << endl;
}
~BaseClass()
{
data = -99;
cout << "_____~BaseClass()____" << endl;
}
void Fun()
{
cout << "_____Fun()____" << data << endl;
}
int data;
};
int main()
{
BaseClass *b = NULL;
{
BaseClass b1(300);
b = &b1;
}
b->Fun();
return 0;
}
Instance b1 is created in a segment and its life is limited to that segment. I am not able to understand how the data and methods are accessible even after destructor.
C++ as a language gives some guarantees and in many areas leaves things undefined. This means, for some code, the standard doesn't mandate any behaviour and anything, as a result, can be done by the compiler. You're in such a situation.
I am not able to understand how the data and methods are accessible even after destructor.
Once the object is destroyed, accessing it, via a pointer (or something else), is undefined. You being able to access it in some instance of the program doesn't matter. In some other situation you may not be able to - changing the machine, the memory management scheme, or any other environmental factor may make the program crash, hang, etc. i.e. the language doesn't guarantee anything here.
As a general rule, you should never write code that invoke undefined behaviour, unless you're trying to learn something.
I'm having trouble understanding why this code works. I've been in the C# world for awhile and wanted to brush up on C/C++ before diving into the new stuff in C++11 like RValue Refs and move semantics.
I'm wondering why this code that I wrote works:
class InnerMember
{
private:
int _iValue;
public:
InnerMember(): _iValue(0) {};
InnerMember(int iValue) : _iValue (iValue) {};
int GetValue(void) { return _iValue; }
int SetValue(int iValue) { _iValue = iValue; }
};
class TestClass
{
private:
InnerMember _objValue;
public:
TestClass() : _objValue(1) {};
void SetValue(int iValue)
{
_objValue.SetValue(iValue);
}
InnerMember& GetRef(void)
{
return _objValue;
}
virtual ~TestClass() { std::cout << "I've been released!" << std::endl; }
};
int main (int argc, char *argv[])
{
TestClass* pobjTest = new TestClass();
std::cout << "Before:" << std::endl;
std::cout << pobjTest->GetRef().GetValue() << std::endl;
pobjTest->SetValue(5);
InnerMember& robjInner = pobjTest->GetRef();
delete pobjTest;
std::cout << "After:" << std::endl;
std::cout << robjInner.GetValue();
return 0;
}
The output is:
Before:
1
I've been released!
After:
5
Press any key to continue...
I thought that this would cause an error, since I access the referenced object InnerMember from TestClass after TestClass has been destroyed. Is there some sort of return value optimization going on? Or is it really returning a copy instead of passing back the reference?
I used GCC to with no optimizations (-O0) and it still ran without an issue.
I also used the -S switch to generate the assembly but my AMD64 knowledge is rusty and the name mangling didn't help.
That is undefined behaviour, which means even the "correct" behaviour could happen. When you delete something in C++, it is not erased from the memory, so accessing it before something else writes over it will sometimes maybe still work.
robjInner is still a reference to some deleted object in memory.
This would lead to undefined behaviour.
After deletion, the reference robjInner has been left dangling. You get back the previous value because no one else claimed that piece of memory yet.
Copied from here
A previously-valid reference only becomes invalid in two cases:
If it refers to an object with automatic allocation which goes out of scope,
If it refers to an object inside a block of dynamic memory which has been freed.
The first is easy to detect automatically if the reference has static scoping, but is still a problem if the reference is a member of a dynamically allocated object; the second is more difficult to assure. These are the only concern with references, and are suitably addressed by a reasonable allocation policy.
You can add a print statement inside InnerMember destructor to see what is going on. You will see InnerMember is destroyed after TestClass and the 5 you get is because no one write to that part of memory yet. But that reference is not valid anymore.
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?
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.