Why does c++ care if I have a pointer in a classes variable list?

Why does c++ care if I have a pointer in a classes variable list?

I understand If I allocate the pointer I need to remember to clean it up. Why do I need a warning about it out of Modern Standards?

the warning reads:
1
2
3
'class SomeClass' has a pointer data member
   but doesn't override SomeClass(const SomeClass&)
   or 'operator=(const Someclass&)



The class I have this for is a single instance class so there is no need for coping the class.
Last edited on
It's telling you that the default copy/operator = will not deep copy the pointer for you. Thus, if you copy the class but do not change them, but try to delete the pointer in the destructor, you will cause double deletions.

Btw...
Why do I need a warning about it out of Modern Standards?
The standard doesn't say anything about warnings.
C++ and the standard don't care, but it's a common mistake/oversight so the compiler is trying to give you a heads up. Arguably you could say the compiler is being over cautious.

The reason why it's probably a mistake is that pointers are not deep copied, therefore any pointer member you have is likely to result in a bad pointer after the copy.

For example, consider the following:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Example
{
private:
  int* ptr;

public:
  Example() : ptr(new int) {}  //allocate the pointer in dtor
  ~Example() { delete ptr; }  // and destroy it in dtor
};

int main()
{
  Example foo; // a new Example

  {
    Example bar = foo; // copy foo to a new example
      // Note this is a big problem, because now bar.ptr == foo.ptr

  }  // bar's dtor runs here.  This delete's foo.ptr!

}  // foo's dtor runs here.  Tries to delete foo.ptr again!  EXPLODE 


Because of this, pointers in a class usually mean the class will need an custom assignment operator and copy ctor, typically to make deep copies of the data pointed to so that above situations are avoided.


Note that this isn't always the case. It's entirely possible to have a pointer member that doesn't demand this special treatment... however that is very uncommon.

EDIT: doh, too slow =(
Last edited on
Thank you for, repeating what I was thinking here for the warning. My coding experience would remind me of things like that without the warning. I fight with how pointers are destroyed in gui libs but not in non-gui coding.
Suggest to use the one of stl pointers , auto_ptr<int> , it can change the ownship fully
Topic archived. No new replies allowed.