As i have read that if we create object through pointer, it wont delete automatically. but when i am calling member function with pointer its giving error
#include <iostream>
using namespace std;
class Base
{
protected:
int i;
public:
Base(){}
Base(int a) { i = a; }
virtual void display()
{ cout << "I am Base class object, i = " << i << endl; }
~Base(){
cout<<"tsp";
}
};
int main()
{
//Base b(33);
{
Base *u=new Base() ;
}
u->display();
//delete u;
return 0;
}
O/P:'u' was not declared in this scope but still the memory exist
The pointer is not being deleted, but u goes out of scope when the block it is declared in ends; u is only available within that block. Therefore, calling u->display() is an error because there is no u variable in scope anymore.
Note that because it's not automatically deleted (going out of scope is not the same thing as being deleted), you are leaking the memory allocated by the Base object.
To put it another way, u points to a Base object but it is not itself the object. The pointer can go away, but the object can still exist. It's like if I had someone's business card and threw it away. Their phone number or email address don't cease to exist just because I threw away my record of it.
"u goes out of scope" is throwing away the business card.
"delete u" is... disconnecting the phone line on the business card, I guess.
Contrast this with the following code, using a smart pointer:
int main() {
std::cout << "top\n";
{
std::unique_ptr<Base> u{new Base()};
}
std::cout << "bottom\n";
}
In this case, when u goes out of scope, the smart pointer will be destructed and the Base allocation will be freed (you will see the output tsp before you see the output bottom).
Related
Why the std::function object(i.e fn) still works well after the object ins is out of scope?
Here is the code snappit(https://godbolt.org/z/Y6KaWY):
#include <iostream>
#include <functional>
std::function<int(void)> fn;
class CTest
{
public:
CTest() {std::cout << "ctor:" << this << std::endl;};
int demo(void){std::cout << "this pointer:" << this << std::endl; return 0;}
};
void assign(void)
{
CTest ins;
fn = std::bind(&CTest::demo, &ins);
}
int foo()
{
return 9;
}
int main()
{
assign();
CTest tes1;
foo();
fn();
}
The outputs:
Program returned: 0
Program stdout
ctor:0x7fff64960a80
ctor:0x7fff64960be0
this pointer:0x7fff64960a80 //You see, still point to the object(i.e `ins`) that is out of its scope
The class CTest has no data members and no virtual methods. When you capture its address (&ins) with std::bind, you store it inside an instance that is assigned to the global variable fn. When you execute CTest::demo() through fn you are passing the captured pointer to the method demo() as the first parameter (this). You are not accessing any members of the class CTest. This is all valid. But since you don't know what the user of fn will do with the stored pointer, that is going to become invalid at the end of assign(), this is classified as undefined behavior.
If you add members to CTest and try to access them from CTest::demo(), then you will be accessing memory that this pointer points to, but that memory is no longer valid and may have been overwritten.
If you add a virtual method and try to execute it from CTest::demo() or even if you make CTest::demo() virtual, you will most likely call invalid functions, because the pointer to the virtual method table is part of the memory that the captured pointer points to and may have been overwritten.
I am currently reading the second edition of C++: A Beginner's Guide by Herbert Schildt.
In Module 9.4, he talks about returning objects:
Just as objects can be passed to functions, functions can return objects. To return an object, first declare
the function as returning a class type. Second, return an object of that type using the normal return
statement. The following program has a member function called mkBigger( ). It returns an object that
gives val a value twice as large as the invoking object.
This is the 'following program' he mentions:
// Returning objects.
#include <iostream>
using namespace std;
class MyClass {
int val;
public:
// Normal Constructor.
MyClass(int i) {
val = i;
cout << "Inside constructor\n";
}
~MyClass() {
cout << "Destructing\n";
}
int getval() { return val; }
// Return an object.
MyClass mkBigger() {
Myclass o(val * 2); // mkBigger() returns a MyClass object.
return o;
}
};
void display(MyClass ob)
{
cout << ob.getval() << '\n';
}
int main()
{
cout << " Before Constructing a.\n";
MyClass a;
cout << "After constructing a.\n\n";
cout << "Before call to display.\n";
display(a);
cout << "After display() returns.\n\n";
cout << "Before call to mkBigger().\n";
a = a.mkBigger();
cout << "After mkBigger() returns.\n\n";
cout << "Before second call to display.\n";
display(a);
cout << "After display() returns.\n\n";
return 0;
}
This gives us the following output:
Before Constructing a.
Inside constructor
After constructing a.
Before call to display.
10
Destructing
After display() returns.
Before call to mkBigger()
Inside constructor
Destructing
Destructing
After mkBigger() returns.
Before second call to display.
20
Destructing
After display() returns.
Destructing
Schildt then goes on to explain that the reason there are two 'Destructing' messages during the mkBigger() call is because of the fact that:
when an object is returned by a function, a temporary object is automatically created, which holds the return value. It is this object that is actually returned by the function. After the value has been returned, this object is destroyed.
I was actually surprised there wasn't 3 'Destructing' messages. I have the following issue: Given the definition of mkBigger(), a new MyClass instance is created, and it is that instance that is returned and placed in the address of a. Thus, when doing
a = a.mkBigger();
My impression is thus that the original object previously held in a is no longer referenced by a. Is this correct? If so, I then have the following issues:
I was told C++ has some minute notions of garbage collection. Would that object thus be garbage-collected? where is this object now? Is this an example of the possible feared memory leaks that many mention when talking about the 'dangers' of C++?
One of the destructor in mkbigger() is called on o, the MyClass instance passed in by value; it goes out of scope at the end of the function. The other is called on the temporary copy of o returned when it is destroyed. What else goes out of scope? Not a in main(); therefore you should not expect a third destructor to be called. C++ does not provide garbage collection outside of calling destructors when automatic objects go out of scope.
Unlike some other modern languages, a does not "hold a reference" to an object; a is the object, in that it is a certain number of bytes holding the raw data members. When you do a = a.mkBigger();, MyClass's default assignment operator is called, which simply copies the val inside the temporary object on the right hand side into the val inside a, overwriting the value that was already there. a = a.makeBigger() would be equivalent to a.val = a.makeBigger().val if val were public.
Memory leaks occur when you use new to allocate memory and then fail to use delete to deallocate that memory. For classes that do this internally, you must write at least your own copy constructor, assignment operator, and destructor.
#include"iostream"
using namespace std;
class base{
public:
void f()
{
cout<<"base f:"<<endl; // prints base f:
}
};
int main()
{
base *b; // even same out put with " base *b =NULL; "
b->f();
return 0;
}
O/p : base f:
can any one please explain how the function is getting called without assigning the object to the pointer .
Thanks.
Call of member-function with not initialized (or initialized to 0) pointer to object is undefined behaviour, however it may works since there is no attempts to access variables of object and there is no vtable here. You can look at this function like
void f_base(base* p)
{
cout << "base f:" << endl;
}
there is no access - there is no error, on all modern-compilers it will work, but it can be changed anytime.
This is invalid code, but since nothing in base::f() accesses a member variable, no invalid memory is getting touched.
If you add a member and try to print it out in the function, you will almost undoubtedly get a crash.
You need to use new
i.e.
base *b; // even same out put with " base *b =NULL; "
should be
base *b = new base;
... Need a delete to prevent memory leaks
So in C++ if I create an object useing new I should always deallocate it using delete
For example
Segment::Segment(float length)
{
segmentLength = length;
angle = 0.0f;
x = Rand::randFloat(1.0f, 1.5f);
y = Rand::randFloat(1.0f, 1.5f);
vx = Rand::randFloat(0.0f, 1.0f);
vy = Rand::randFloat(0.0f, 1.0f);
prevX = Rand::randFloat(0.0f, 1.0f);
prevX = Rand::randFloat(0.0f, 1.0f);
};
And lets say I use it like this in another class such as,
this._segmentObject = Segment(2.0f);
this._segmentPointer = new Segment(2.0f);
In the destructor of that class, I know I should call delete on the this._segmentPointer, however how do I make sure memory is deallocated for the other one?
however how do I make sure memory is deallocated for the other one?
It is automatically. This is why this type of storage is called automatic. Automatic storage is released at the end of the storage’s life cycle, and the objects’ destructors called.
The object life-cycle ends when the program control leaves the scope where the object has been allocated.
Things not allocated with new, new[] or the malloc family should be destructed and "freed" when the object goes out of scope.
Often this simply means that that the code has reached the end of the block it was declared it or that the object that it was in was destructed (one way or another).
To see this in action, you can do something like this:
struct C {
C() { std::cout << "C()" << std::endl; }
~C() { std::cout << "~C()" << std::endl; }
};
struct B {
B() { std::cout << "B()" << std::endl; }
~B() { std::cout << "~B()" << std::endl; }
private:
C c_;
};
struct A {
A() { std::cout << "A()" << std::endl; }
~A() { std::cout << "~A()" << std::endl; }
};
int main() {
B *b = new B; // prints "B()", also constructs the member c_ printing "C()"
{ // starts a new block
A a; // prints "A()";
} // end of block and a's scope, prints "~A()"
delete b; // prints "~B()", also destructs member c_, printing "~C()"
}
Note: that if we did not do delete b, the "~B()" and "~C()" would never print. Likewise, if c_ were a pointer allocated with new, it would need to be delete'd in order to print "~C()"
The memory for this._segmentObject is part of the memory of the containing object, and will be released when the containing object is destroyed.
this._segmentObject is assigned from a temporary object that is created on the stack and deleted when it goes out of scope.
Not only that, You should only allocate with new and deallocate with delete in Constructors or Destructors, otherwise your program can leak if an exception is thrown.
The destructors for all class-type member objects are called at the time of the destruction of the primary class. So your this object, which is allocated on the stack, will have it's destructor called when it goes out-of-scope. At that time, any class-type member objects of your this object will have their own destructors called in addition to the destructor for your this object which will call delete on the member pointer.
For instance, take the following code sample:
#include <iostream>
using namespace std;
class A
{
public:
A() {}
~A() { cout << "Destructor for class A called" << endl; }
};
class B
{
private:
A a;
public:
B() {}
~B() { cout << "Destructor for class B called" << endl; }
};
int main()
{
B b;
return 0;
}
When run, the output becomes the following:
Destructor for class B called
Destructor for class A called
So you can see that when b, which is allocated on the stack, goes out-of-scope at the end of main, the destrutor for class B is called, which in-turn, after executing the body of the destructor function, calls the destructors for any of its class-type member data objects, which in this case would mean the destructor for class A. Therefore in your case, the pointer would have delete called on it in the destructor for your this class, and then the destructor for _segmentObject would be called after the destructor for this had completed execution of the body of its destructor. Then once all the destructors for the non-static data-member objects had been called, the destructor for this then returns.
The _segmentObject is allocated automatically on the stack.
The object destructor will be called automatically when the variable gets out of scope.
As others have said, you don't need to explicitly do anything to reclaim the memory used by this._segmentObject. As soon as it goes out of scope, the memory will be reclaimed.
It's not clear why you would use Segment in both ways. You should try to ensure you use the Resource Acquisition Is Initialization idiom, as it removes much of the need for checking new / delete pairs. That is, just use the this._segmentObject version, not the pointer.
Your application may not allow it, though.
// AirlineTicket.h
class AirlineTicket
{
public:
AirlineTicket();
~AirlineTicket();
int getNumberOfMiles();
private:
int mNumberOfMiles;
};
I want now what is the meaning of ~AirlineTicket(); in this code?
I don't know the meaning of ~ (tilde).
It is the destructor.
It gets called when you destroy (reaching end of scope, or calling delete to a pointer to) the instance of the object.
In the context you're using it, it defines a destructor.
In other context such as the following one, it's also called bitwise negation (complement):
int a = ~100;
int b = ~a;
Output: (ideone)
-101
100
~ signs that it is a destructor and when ever the object goes out of scope, corresponding destructor is called.
When the destructor is called ?
Taking an example -
#include <iostream>
class foo
{
public:
void checkDestructorCall() ;
~foo();
};
void foo::checkDestructorCall()
{
foo objOne; // objOne goes out of scope because of being a locally created object upon return of checkDestructorCall
}
foo:: ~foo()
{
std::cout << "Destructor called \t" << this << "\n";
}
int main()
{
foo obj; // obj goes of scope upon return of main
obj.checkDestructorCall();
return 0;
}
Results on my system:
Destructor called 0xbfec7942
Destructor called 0xbfec7943
This example just serves to indicate when a destructor is called. But destructor is written only when the class manages resources.
When class manages resources?
#include <iostream>
class foo
{
int *ptr;
public:
foo() ; // Constructor
~foo() ;
};
foo:: foo()
{
ptr = new int ; // ptr is managing resources.
// This assignment can be modified to take place in initializer lists too.
}
foo:: ~foo()
{
std::cout << "Destructor called \t" << this << "\n";
delete ptr ; // Returning back the resources acquired from the free store.
// If this isn't done, program gives memory leaks.
}
int main()
{
foo *obj = new foo;
// obj is pointing to resources acquired from free store. Or the object it is pointing to lies on heap. So, we need to explicitly call delete on the pointer object.
delete obj ; // Calls the ~foo
return 0;
}
Results on my system:
Destructor called 0x9b68008
And in the program, you posted I don't see a need to write destructor. Hope it helps !
It's the class destructor. You might want to pick up an introductory text on C++ development, as destructors are a fundamental concept in OOP. There is a good reference site here, and the C++ FAQ is another good resource.
~AirlineTicket(); is the destructor for the class AirlineTicket
see this link for further reference
The destructor is called when you delete the object of that class, to free any memory allocated or resources being used by the object.
~ introduces a destructor. It's used because (a) it was available, ad (b) ~ is one (of several) mathematical notation for "not".
This indicates destructor of class.
http://publib.boulder.ibm.com/infocenter/comphelp/v8v101/index.jsp?topic=%2Fcom.ibm.xlcpp8a.doc%2Flanguage%2Fref%2Fcplr380.htm