I have a class, which contains some allocated pointers (reduced to 1 in the example), and I would like not to have to deep copy when the copy operator is called. The class is the following:
class Example {
public:
Example() : ptr1(0), len1(0) {}
Example(const Example& other) : ptr1(0), len1(0) {
if (other.ptr1) {
ptr1 = other.ptr1;
len1 = other.len1;
}
}
~Example() {
if (ptr1)
delete[] ptr1;
}
char* ptr1;
int len1;
};
A reasonable use after free happens when I try to create some Example class, assign the pointers, and insert it into a cointainer that has scope outside the function in which assingment and insertion happens :
// some function
{
Example a;
a.ptr1 = new char[1];
vec.push_back(Example); // some std::vector<Example> I created outside the function call.
}
I know by deep copying that this could be solved. Or by inserting an empty Example and then operate with the Example copy that the map saved, but I would like to know if there are more options. The sandard I'm using is C++11.