Sign in to follow this  
Calin

copy a pointer to a class member

Recommended Posts

class cat
{
father * Dad;
AddFather(father * F);
}

void cat::AddFather(father * F)
{
Dad = F;
}

// main()
father * F1;
cat.AddFather(F1);



Is this how it's done? [Edited by - Calin on March 14, 2009 7:14:28 AM]

Share this post


Link to post
Share on other sites
Quote:
Original post by Calin
*** Source Snippet Removed ***
Is this how it's done?
I don't see anything wrong with your code (other than some syntax errors, and the fact that it's not a complete, compilable program).

Be aware though that passing around raw pointers like that is fairly error-prone; improper handling of ownership can easily lead to double deletions and/or dangling pointers.

You can certainly get away with it if you know what you're doing, but keep in mind that there are safer ways to do this sort of thing. For example, in this particular case a 'weak reference' smart pointer (such as boost::weak_ptr) might be an appropriate solution.

Share this post


Link to post
Share on other sites
Thanks for comments
When does a pointer "dangle"?

[Edited by - Calin on March 14, 2009 9:15:40 AM]

Share this post


Link to post
Share on other sites

int *p, *q;

p = new int( 42 ); // create an int, assign its address to p
q = p; // assign the int's address to p
delete p; // the int no longer exists

// q still points to what p was pointing to
// however, that memory has since been deleted

std::cout << *q; // Boom!




You also might want to look at the Wiki's Dangling Pointer Article.

Share this post


Link to post
Share on other sites
so calling delete you remove both the content of the memory cell and the variable holding the address of the MC

Share this post


Link to post
Share on other sites
Calling delete tells the OS that the memory that was allocated is now free and can be used somewhere else. Basically in _fastcall's example you can think like the memory address that p was pointing to now does not exist in the context of your program after calling delete p until that memory address is used again when you allocate something using new keyword.



Share this post


Link to post
Share on other sites
From your post though it looks like you are new to C++ so I would suggest you avoid boost libraries until you get a better handle at C++. It's a good thing to know about it - just that it may not be the wisest to use it if you are very new to C++ and pointers in general.

If you understand pointers well then it will give you a better insight into why what jyk said is a better way to do something

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this