Reputation: 403
In the following code , I have created a class named ele, and I'm trying to store ele objects in a vector v. I am using deep copy by delegating copy constructor to the constructor with integer as an argument. I am getting an unusual error , a header file allocator.h opens up in my IDE(devC++) when I try to run it and I don't know what's going wrong.
If I comment out the copy constructor, the program runs with shallow copying without any compiler errors ( however, that is not what I want to do )
#include <iostream>
#include <vector>
using namespace std;
class ele{
public:
int* data_ptr;
ele(int a) {
data_ptr=new int;
*data_ptr=a;
cout<<"new ele created with data="<<*data_ptr<<endl;
}
ele(ele &s):ele(*s.data_ptr) {
cout<<"object with data="<<*data_ptr<<" copied"<<endl;
}
~ele(){
cout<<*data_ptr<<"destroyed"<<endl;
delete data_ptr;
}
};
void display(ele a){
cout<<*a.data_ptr<<endl;
}
ele create(int k){
ele* a=new ele(k);
return *a;
}
int main(){
vector <ele> v;
int t=10;
while(--t)
{
v.push_back(create(t));
}
}
Upvotes: 0
Views: 318
Reputation: 5215
This is because your copy constructor should take a const ele &
ele(const ele &s):ele(*s.data_ptr) {
cout<<"object with data="<<*data_ptr<<" copied"<<endl;
}
Upvotes: 1