copy a pointer to a class member

Started by
6 comments, last by Calin 15 years, 1 month ago

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]

My project`s facebook page is “DreamLand Page”

Advertisement
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.
Thanks for comments
When does a pointer "dangle"?

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

My project`s facebook page is “DreamLand Page”

int *p, *q;p = new int( 42 ); // create an int, assign its address to pq = p; // assign the int's address to pdelete p; // the int no longer exists// q still points to what p was pointing to// however, that memory has since been deletedstd::cout << *q;   // Boom!


You also might want to look at the Wiki's Dangling Pointer Article.
so calling delete you remove both the content of the memory cell and the variable holding the address of the MC

My project`s facebook page is “DreamLand Page”

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.



The more applications I write, more I find out how less I know
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

The more applications I write, more I find out how less I know
k, thanks for advices

My project`s facebook page is “DreamLand Page”

This topic is closed to new replies.

Advertisement