I'm trying to understand Deep Copy. But I'm just confused about allocating dynamically memory by calling Constructor.
Here is my successful program for Deep copy:
#include<iostream>
using namespace std;
class A{
public:
int *p;
A(){
p=new int;
}
void set(int b){
*p=b;
}
int get(){
return *p;
}
void operator=(const A &k){
p = new int;
*p=*(k.p);
}
~A(){
delete p;
}
};
int main()
{
A obj;
obj.set(3);
A obj1;
obj1=obj;
obj1.set(5);
cout << obj.get() << endl;
cout << obj1.get() << endl;
}
Now I just want to ask that I created two objects and constructor will call for two times and in constructor there dynamically memory is allocating.
Then My Question is that pointer should point two different dynamically memory location(2 object and 2 pointer) or is pointer same as Static data members(then no deep copy should require)? Mean one pointer for all objects of class.
If you create two instances of that class, they will have two different p members each containing a different address of different regions in memory, yes.
You can probably tell if you run your program: it will display 3 and 5, if the pointer was the same, it would have displayed 5 twice.
Edit: as asked, some additional explanation (and a summary of what have been said in the comments)
First of all, your operator= is leaking memory, instead you should remember to release the memory already allocated in p before reassigning it:
void operator=(const A &k){
delete p;
// as JoshuaGreen states in the comments, you can set p to nullptr
// here, that way, if new fails and throws, p will be set to nullptr
// and you'll know it doesn't contain anything (you'll have to test
// it in other methods to benefit from this modification though,
// but it will be safer)
p = nullptr;
p = new int;
*p=*(k.p);
}
Although in this specific case, you could just avoid reallocating:
void operator=(const A &k){
// p = new int; // not needed
*p=*(k.p);
}
Now, that was indeed important to overload the assignment operator= (and you actually forgot to overload the copy constructor), let's see what would have happened if this assignment operator= wasn't defined.
Your class would instead look like this:
#include<iostream>
using namespace std;
class A{
public:
int *p;
A(){
p=new int;
}
void set(int b){
*p=b;
}
int get(){
return *p;
}
~A(){
delete p;
}
};
But actually, the compiler will generate an implicitly defined default copy constructor and default assignment operator= for you. Of course you don't see their implementation, but they would behave exactly the same as if the class was defined like this:
#include<iostream>
using namespace std;
class A{
public:
int *p;
A(){
p=new int;
}
A(const A& other) :
p(other.p) {} // ! we're copying the pointer instead of reallocating memory
void set(int b){
*p=b;
}
int get(){
return *p;
}
A& operator=(const A& other){
p = other.p; // same here!
}
~A(){
delete p;
}
};
When you're class deals with dynamically allocated memory, that's bad. Let's see what would happen in your main:
int main()
{
// allocate a new pointer to int, let's call it p
A obj;
// set the content of p to 3
obj.set(3);
// allocate a new pointer to int, let's call it p1
A obj1;
// /!\
// instead of copying the content of p to the content of p1, we're
// actually doing p1 = p here! we're leaking memory AND the two
// objects point on the same memory!
obj1=obj;
// set the content of p1 to 5, but p1 is now equal to p because of
// the bad assignment, so we're also setting p's content to 5
obj1.set(5);
// print the content of p (5)
cout << obj.get() << endl;
// print the content of p1 (5)
cout << obj1.get() << endl;
}
// delete the contents of p and p1 /!\ we're actually deleting the same
// allocated memory twice! that's bad
That's why you have to redefine the "big three" (copy constructor, copy assignment operator, and destructor)
Related
I want to know is it okay if i will use following method? There is no syntax errors and any warnings but i want to know is there any memory problems?
#include <iostream>
using namespace std;
class test {
int* x;
public:
test(int *n) { this->x = new int(*n); }
inline int get() { return *x; }
~test() { delete x; }
};
int main(void) {
while(1){
test a(new int(3));
cout << a.get() << endl;
}
return 0;
}
You have 2 issues in your code:
your class violates rule of three/five/zero
you are leaking memory when create a
In this code:
test a(new int(3));
you dynamically allocate int with value 3 and pass to a ctor which uses value and creates it's own dynamically allocated int. After that this memory is leaked. If you want to pass dynamically allocated data to a class use a smart pointer:
class test {
std::unique_ptr<int> x;
public:
test(std::unique_ptr<int> n) : x( std::move( n ) ) { }
int get() const { return *x; }
};
int main()
{
x a( std::make_unique<int>( 3 ) ); // since c++14
x a( std::unique_ptr<int>( new int(3) ) ); // before c++14
...
}
and you do not need to implement dtor explicitly, you do not violate the rule and it is safe to pass dynamically allocated data to ctor.
Note: I assumed you used int as example and you would understand that dynamically allocate one int is useless, you should just store it by value.
You are violating the rule of 3 (5 since c++11). It means that since you defined the destructor you should define the copy/move constructor/operation.
With your implementation, the copy/move constructor/operation are wrong. When you copy your object, it will do a shallow copy of your pointer and will delete it therefore you will have a double delete. When you move it, you will delete a pointer you didn't allocated.
Bonus point: your inline is useless
#include <iostream>
class Object {
public:
int x;
Object() { }
Object(int x) {
this->x = x;
}
};
class SomeClass {
public:
Object array[10];
int n;
SomeClass() { n = 0; }
void insert(Object o) {
array[n++] = o;
}
};
int main() {
SomeClass s;
Object test = Object(4);
s.insert(test);
return 0;
}
I have this example where I pre-allocate an array of objects in SomeClass and then in some other method, main in this example, I create another object and add it to the array in SomeClass
One thing I think I should do is to switch from array[10] to an array of pointers so that I only create objects when I really need to.
But my question is what happens to the memory originally allocated for array[0] when I do "array[n++] = o" replacing it by the new object "o"? does it get de-allocated?
No, nothing happens. The object's assignment operator gets invoked, to replace the object.
For this simple class, the assignment operator is the default operator which, more or less, copies each of the object's members, one at a time.
(No need to get into move operators, etc..., just yet)
I am a newbie to c++ and just learning by reading a book.
So the question may be a bit stupid.
Here is my program:
#include <iostream>
using namespace std;
class Fish
{
public:
virtual Fish* Clone() = 0;
};
class Tuna : public Fish
{
public:
Tuna(const Tuna& SourceTuna)
{
cout << "Copy Constructor of Tuna invoked" << endl;
}
Tuna* Clone()
{
return new Tuna(*this);
}
};
I have question on
return new Tuna(*this);
First, why does the copy constructor return a pointer of Tuna?
Usually, invoking the copy constructor will return a copied instance directly.
For example:
class Student
{
public:
Student(){}
Student(const Student& Input) { cout << "Copy Ctor Invoked\n"; }
};
int main()
{
Student a;
Student b(a);
return 0;
}
Base on my understanding, what Student b(a); does is copying an instance of a and named b.
So why does new Tuna(*this) is not returning an instance instead of a pointer?
Second, why is point of this,ie. *this , provided in the argument?
Base on my understanding this is a pointer to the current object, which mean *this is a pointer to the pointer of the current object. I try to use int to simulate the situation.
// The input argument is the same as a copy constructor
int SimulateCopyConstructor(const int& Input){ return 0; }
void main()
{
int a = 10; // a simulate an object
int* b = &a; // b is a pointer of object a, which simulate "this"
int** c = &b; // c is a pointer to pointer of object a, which simulate of "*this"
SimulateCopyConstructor(a); // It can compile
SimulateCopyConstructor(b); // cannot compile
SimulateCopyConstructor(c); // cannot compile
}
I think sending (*this) to copy constructor is similar to the situation c above. But it does not compile. So how does it works?
Student b(a);
Does not return a Student object. It declares it and instructs compiler to call a copy contructor on the new object allocated on stack.
new Student(a);
This indeed returns a pointer to a new Student object because operator new does. And (a) there instructs the compiler to call a copy contructor on that object that was allocated by new.
However if you had a function doing this:
Student foo(){ return Student(a); }
That would create a new Student object on stack, call copy constructor and then return the resulting object from the function.
Does the following code fragment leak? If not, where do the two objects which are constructed in foobar() get destructed?
class B
{
int* mpI;
public:
B() { mpI = new int; }
~B() { delete mpI; }
};
void foobar()
{
B b;
b = B(); // causes construction
b = B(); // causes construction
}
The default copy assignment operator does a member-wise copy.
So in your case:
{
B b; // default construction.
b = B(); // temporary is default-contructed, allocating again
// copy-assignment copies b.mpI = temp.mpI
// b's original pointer is lost, memory is leaked.
// temporary is destroyed, calling dtor on temp, which also frees
// b's pointer, since they both pointed to the same place.
// b now has an invalid pointer.
b = B(); // same process as above
// at end of scope, b's dtor is called on a deleted pointer, chaos ensues.
}
See Item 11 in Effective C++, 2nd Edition for more details.
Yes, this does leak. The compiler automatically provides an extra method because you have not defined it. The code it generates is equivalent to this:
B & B::operator=(const B & other)
{
mpI = other.mpI;
return *this;
}
This means that the following stuff happens:
B b; // b.mpI = heap_object_1
B temp1; // temporary object, temp1.mpI = heap_object_2
b = temp1; // b.mpI = temp1.mpI = heap_object_2; heap_object_1 is leaked;
~temp1(); // delete heap_object_2; b.mpI = temp1.mpI = invalid heap pointer!
B temp2; // temporary object, temp1.mpI = heap_object_3
b = temp1; // b.mpI = temp2.mpI = heap_object_3;
~temp1(); // delete heap_object_3; b.mpI = temp2.mpI = invalid heap pointer!
~b(); // delete b.mpI; but b.mpI is invalid, UNDEFINED BEHAVIOR!
This is obviously bad. This is likely to occur in any instance that you violate the rule of three. You have defined a non-trivial destructor and also a copy constructor. You have not defined a copy assignment, though. The rule of three is that if you define any of the above, you should always define all three.
Instead, do the following:
class B
{
int* mpI;
public:
B() { mpI = new int; }
B(const B & other){ mpI = new int; *mpi = *(other.mpI); }
~B() { delete mpI; }
B & operator=(const B & other) { *mpI = *(other.mpI); return *this; }
};
void foobar()
{
B b;
b = B(); // causes construction
b = B(); // causes construction
}
You're constructing three objects, and all will be destructed. The problem is that the default copy-assignment operator will do a shallow copy. That means the pointer is copied over, which causes it be be deleted more than once. This causes undefined behavior.
This is the reason behind the rule of 3. You have a destructor but not the other two. You need to implement a copy constructor and copy assignment operator, both of which should do a deep copy. This means allocating a new int, copying the value over.
B(const B& other) : mpI(new int(*other.mpI)) {
}
B& operator = (const B &other) {
if (this != &other)
{
int *temp = new int(*other.mpI);
delete mpI;
mpI = temp;
}
return *this;
}
As pointed out several times, you've violated the rule of three. Just to add to the links, there is a great discussion of this on stack overflow: What is The Rule of Three?
Just to offer a different approach to solving the problems of the code I originally posted, I think I could keep the pointer in class B, but take the memory mangement out. Then I need no custom destructor, and so I don't violate the rule of 3...
class B
{
int* mpI;
public:
B() {}
B(int* p) { mpI = p; }
~B() {}
};
void foobar()
{
int* pI = new int;
int* pJ = new int;
B b; // causes construction
b = B(pI); // causes construction
b = B(pJ); // causes construction
delete pI;
delete pJ;
}
Sorry for the basic question, but I'm having trouble finding the right thing to google.
#include <iostream>
#include <string>
using namespace std;
class C {
public:
C(int n) {
x = new int(n);
}
~C( ) {
delete x;
}
int getX() {return *x;}
private:
int* x;
};
void main( ) {
C obj1 = C(3);
obj1 = C(4);
cout << obj1.getX() << endl;
}
It looks like it does the assignment correctly, then calls the destructor on obj1 leaving x with a garbage value rather than a value of 4. If this is valid, why does it do this?
If there is a class C that has a constructor that takes an int, is this code valid?
C obj1(3);
obj1=C(4);
Assuming C has an operator=(C) (which it will by default), the code is valid. What will happen is that in the first line obj1 is constructed with 3 as a the parameter to the constructor. Then on the second line, a temporary C object is constructed with 4 as a parameter and then operator= is invoked on obj1 with that temporary object as a parameter. After that the temporary object will be destructed.
If obj1 is in an invalid state after the assignment (but not before), there likely is a problem with C's operator=.
Update: If x really needs to be a pointer you have three options:
Let the user instead of the destructor decide when the value of x should be deleted by defining a destruction method that the user needs to call explicitly. This will cause memory leaks if the user forgets to do so.
Define operator= so that it will create a copy of the integer instead of a copy of the value. If in your real code you use a pointer to something that's much bigger than an int, this might be too expensive.
Use reference counting to keep track how many instances of C hold a pointer to the same object and delete the object when its count reaches 0.
If C contains a pointer to something, you pretty much always need to implement operator=. In your case it would have this signature
class C
{
public:
void operator=(const C& rhs)
{
// For each member in rhs, copy it to ourselves
}
// Your other member variables and methods go here...
};
I do not know enough deep, subtle C++ to explain the problem you are encountering. I do know, however, that it's a lot easier to make sure a class behaves the way you expect if you follow the Rule of Three, which the code you posted violates. Basically, it states that if you define any of the following you should define all three:
Destructor
Copy constructor
Assignment operator
Note as well that the assignment operator implementation needs to correctly handle the case where an object is assigned to itself (so-called "self assignment"). The following should work correctly (untested):
#include <iostream>
#include <string>
using namespace std;
class C {
public:
C(int n) {
x = new int(n);
}
C(const C &other): C(other.getX()) { }
~C( ) {
delete x;
}
void operator=(const C &other) {
// Just assign over x. You could reallocate if you first test
// that x != other.x (the pointers, not contents). The test is
// needed to make sure the code is self-assignment-safe.
*x = *(other.x);
}
int getX() {return *x;}
private:
int* x;
};
void main( ) {
C obj1 = C(3);
obj1 = C(4);
cout << obj1.getX() << endl;
}
Basically you are trying to re-implement a smart pointer.
This is not trivial to get correct for all situations.
Please look at the available smart pointers in the standard first.
A basic implementation (Which will fail under certain situations (copy one of the standard ones to get a better one)). But this should cover the basics:
class X
{
int* data;
public:
// Destructor obvious
~X()
{
delete data;
}
// Easy constructor.
X(int x)
:data(new int(x))
{}
// Copy constructor.
// Relatively obvious just do the same as the normal construcor.
// Get the value from the rhs (copy). Note A class is a friend of
// itself and thus you can access the private members of copy without
// having to use any accessor functions like getX()
X(X const& copy)
:data(new int(copy.x))
{}
// Assignment operator
// This is an example of the copy and swap idiom. This is probably overkill
// for this trivial example but provided here to show how it is used.
X& operator=(X const& copy)
{
X tmp(copy);
this->swap(tmp);
return this;
}
// Write a swap() operator.
// Mark it is as no-throw.
void swap(X& rhs) throws()
{
std::swap(data,rhs.data);
}
};
NEW:
What's happening is that your destructor has deallocated the memory allocated by the constructor of C(4). So the pointer you have copied over from C(4) is a dangling pointer i.e. it still points to the memory location of the deallocated memory
class C {
public:
C(int n) {
x = new int(n);
}
~C( ) {
//delete x; //Don't deallocate
}
void DeallocateX()
{
delete x;
}
int getX() {return *x;}
private:
int* x;
};
int main(int argc, char* argv[])
{
// Init with C(3)
C obj1 = C(3);
// Deallocate C(3)
obj1.DeallocateX();
// Allocate memory and store 4 with C(4) and pass the pointer over to obj1
obj1 = C(4);
// Use the value
cout << obj1.getX() << endl;
// Cleanup
obj1.DeallocateX();
return 0;
}
Be explicit about ownership of pointers! auto_ptr is great for this. Also, when creating a local don't do C obj1 = C(3) that creates two instances of C and initializes the first with the copy constructor of the second.
Heed The Guru.
class C {
public:
C(int n) : x(new int(n)) { }
int getX(){ return *x; }
C(const C& other) : x(new int(*other.x)){}
C& operator=(const C& other) { *x = *other.x; return *this; }
private:
std::auto_ptr<int> x;
};
int main() {
C obj1(3);
obj1 = C(4);
std::cout << obj1.getX() << std::endl;
}
When are you testing the value of obj1? Is it after you leave the scope?
In your example, obj1 is a stack object. That means as soon as you leave the function in which it defined, it gets cleaned up (the destructor is called). Try allocating the object on the heap:
C *obj1 = new C(3);
delete obj1;
obj1 = new C(4);