Using a pointer to copy construct

Hey all, I'm trying to debug a memory leak on close of someone else's code, and I wondered if it might be occurring because of the way they have their copy constructor set up. Instead of the usual reference passing, it instead contains a pointer, like so:

1
2
3
4
5
6
SomeClass::SomeClass(SomeClass *smCl)
{
    value1 = smCl->value1;
    value2 = smCl->value2;
    etc
}

Now, my question is, would that screw up any attempt you make to copy a pointer's address?

So if you did:
1
2
SomeClass* ptrA = new SomeClass();
SomeClass* ptrB = ptrA;

Would ptrB point towards the same object as ptrA, or a copy, due to the above function?
No, the above function is not a copy constructor and will not be invoked by line 2 in the second code snippet.

Read the first section here: http://www.cplusplus.com/articles/jsmith1/

EDIT: Note that even a proper copy constructor will not be invoked by line 2, since line 2 is simply copying
a pointer.
Last edited on
Ok, thanks jsmith.

If it's not a recognised copy constructor then, I assume that means a compiler would ignore it when an actual copy of the data is attempted?

That might explain the memory leaks, as the class contains a pointer that is presumably being shallow copied by mistake.
Yes.

But the strange thing is that if SomeClass's destructor actually freed the memory, then I would expect the lack
of a correct copy constructor and/or assignment operator would not result in memory leaks, but would rather
result in heap corruptions.
hello wee bull,

there're only pointers. at your example only new will call the contructor. there will be a memory leak when no one calls delete on ptrA or ptrB (not on both of course)

Now, my question is, would that screw up any attempt you make to copy a pointer's address?

you don't use the address of the pointer just the pointer itself. that's completely ok.


Would ptrB point towards the same object as ptrA, or a copy, due to the above function?

well since you only copy the pointer so, yes, ptrB and ptrA are pointing towards the same object (and no constructor is involved)
Topic archived. No new replies allowed.