passing pointer from function

I wrote a program that's supposed to manipulate a bitmap pointer and return itin a function as so:
bitmap* getbitmap()
{
return b;
}
If I do this does the program lose control or scope of the bitmap pointer? (i.e it can't use it again?)
Depends where the bitmap that 'b' is pointing to is created.
it would be created in the program that's passing it off.
Heres what a stripped down version would look like:
(bitmap b would be declared in the header file as private
#include whatever.h
whatever::whatever()
{
b = 0;
}
bitmap* whatever::getbitmap()
{
return b;
}
**** other methods that manipulate b ****
whatever::~whatever()
{
destroy(b); //special function to release b from memory
}
Then it's ok.

And remember not to delete the pointer outside your class.

And if you don't intend to change the object returned, which is probably the case, you should return a const bitmap *.

And your constructor is better expressed as

1
2
3
4
whatever::whatever()
	: b(0) // or better yet, b(nullptr)
{
}
The bitmap won't be changed outside of the program, but it will be updated every cycle of the program (going through while loop). I just need it to be visible to the program using whatever an an object.

I got a huge memory leak issue in my program, I got 2 headers, one declared inside the other and I'm trying to narrow down the possibilities of where it might be coming from. Error message range from double free, incorrect checksum returned from something or other, and unaligned pointer being freed.
Are you making copies of whatever? If you are, make sure the copy constructor and assignment operators ensure exclusive ownership of the pointer. I'm just guessing, because I can't give a better answer without going through your code. But this kind of errors mean you are not handling pointers correctly.

It's hard to discover where these problems come from. I suggest reducing your code to the minimum necessary to reproduce the error and carefully examining the code involved.
Its not being copied in any way, but there are 2 instances of whatever being declared, and they do use each other as function parameters:

void whatever::checkhit(whatever other)
{
if other.getx() > x)
{
//blah blah blah
}
}

But if I was copying it how would I ensure exclusive ownership?
You have to define a copy constructor and an assignment operator that do deep copies. The default ones will just copy the pointer, not what the pointer points to.

http://en.wikipedia.org/wiki/Object_copy
http://en.wikipedia.org/wiki/Copy_constructor
Topic archived. No new replies allowed.