pointers! yah!

Started by
8 comments, last by iMalc 19 years, 7 months ago
Aight, here's my latest query. Is is possible to have a function return a pointer and have it so that if you deleted the pointer that the function assigned to not kill the original pointer when the external one is deleted? Now that I'm sure I've butchered that question, how about an example ;)

int* foo()
{
    return this->some_ptr;
}

int *ext_ptr = foo();
delete ext_ptr;  // kills this->some_ptr as well as ext_ptr


(yes, I know that non-member functions don't have this-> just bear with me for the sake of example ;) Basically, is there a way to return a reference to a pointer or something, so it doesn't delete the member pointer? Thanks!
"Game Programming" in an of itself does not exist. We learn to program and then use that knowledge to make games.
Advertisement
It's been a couple of month since I've *looked* at C/C++ code (school now is assembler, java, and my attempts to install Debian), but I hope this helps...

If a function foo() allocates space for an integer and returns a pointer to that integer in memory, well if you use the delete operator on it, that integer is gone, the memory is deallocated. That's what delete does.

The *pointer* at that point still points at something, but that something is unallocated memory that you should NOT try to access. =) Delete makes the integer go away.

So, in your case..

int *foo(){   int *i = new int; // allocate space   *i = 4;           // stick in an arbitary number   return i;         // return the pointer}...delete i;            // no more 4, i points at that space stilli = NULL;            // a good failsafe after you deallocate.


If you do try to access i after using delete, and it's not set to NULL...well, you will confront one of the elusive and evil run-time bugs that C/C++ has become famous for.

If you're running in Windows, you might get "lucky" and experience a General Protection Fault. Otherwise you might poke another process...which will not make you a happy programmer.
One way or another, you will have to make a copy. The simplest way is to just return the value (not the pointer or reference).
int foo(){    return *(this->some_ptr);}int ext_ptr = foo();

Now you don't have to worry about pointers at all.

If you really want a pointer, well, you can allocate some new memory:
int* foo(){    return new int(this->some_ptr); // copy constructor}int ext_ptr = foo();delete *ext_ptr;

Of course, now you've got to remember to delete ext_ptr or you'll be leaking memory and, if it mattered, ext_ptr and some_ptr point to different memory locations.

When all is said and done, the most elegant solution is probably to ditch "dumb" pointers and to use smart pointers which do automatic reference counting (that is, the object is deleted if and only if all the smart pointers "go away")

// Make a typedef for conveniencetypedef boost::shared_ptr<int> sp_int;sp_int foo(){    return sp_int(this->some_ptr);}sp_int ext_ptr = foo();// no delete required!*ext_ptr = 3; // does modify the member, just as with dumb pointers


Of course, that implies building your entire application around smart pointers, 'extracting' the dumb pointer they contain only where really necessary (e.g. to talk to 3rd-party APIs).
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan
First off, please don't take my critisism offensively, but to the previous poster (Fruny), why would you bring smart pointers into this discussion when the very question that was posted implies a beginner. I have never understood why people do this, is it to show off their knowledge? To me, it just seems counter-productive to talk about smart pointers to someone not understanding the way normal pointers really work to begin with.

This is also surprising given you fact that you are a moderator.
Maybe because smart pointers can help beginners write correct code? I agree that some people drag way overcomplicated stuff into some discussions, but in this case the suggestion was helpful.
Isn't OOP about using components without having to worry about their internals?

Smart pointers may be complicated internally, but they are much simpler to use than manual memory-management. Same thing with std::vector versus manually-allocated arrays. Modern tools allow you to be productive now. There is plenty of time to learn about implementation details later, if you are inclined to.

As for showing off... I don't feel I have anything to prove. [rolleyes] The question was ambiguous enough that you can't tell whether we really are dealing with a beginner, or someone asking for a technical trick.
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan
I understand and thanks for cleary things up form me. I guess I was looking at it from my point of view in that when I come across a new programming "tool" I have a hard time using it without the desire to know how it works. So given the fact that I was assuming this question was more of a beginner question it was easy for me to jump to the conclusions I had. My apologies for the confusion.
Quote:Original post by pammatt
First off, please don't take my critisism offensively, but to the previous poster (Fruny), why would you bring smart pointers into this discussion when the very question that was posted implies a beginner. I have never understood why people do this, is it to show off their knowledge? To me, it just seems counter-productive to talk about smart pointers to someone not understanding the way normal pointers really work to begin with.

This is also surprising given you fact that you are a moderator.


boost::shared_ptr is designed to solve the question that was asked; gotta learn about them sometime ;)
- The trade-off between price and quality does not exist in Japan. Rather, the idea that high quality brings on cost reduction is widely accepted.-- Tajima & Matsubara
No need to apologize. Looking at the guts of library can be very instructive (and in both the STL and Boost's case, you got the full source, so feel free to learn from them both). But too often I see people insist that a beginner must learn all the nitty-gritty details before even trying to write a real program (and C++ does have a lot of details you have to take care of). Taken to the extreme, purists shouldn't even use operating systems, graphics libraries and the like until they know how they are implemented [smile]
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan
I get the impression from your question that you may have a design problem i.e. your problem could best be solved in another manner.
Maybe you need to more closely follow some things like RAII or have a clear thinking of what owns each thing you allocate or make sure that things are allocated and deallocated by the same functional part.

It's just a suggestion, it's possible you need to do what you're doing, but there is virtually always a better way.
"In order to understand recursion, you must first understand recursion."
My website dedicated to sorting algorithms

This topic is closed to new replies.

Advertisement