72 points · by olouv · 12y ago · 78 comments
I think this is by far the most important piece of advice in that thread. It gets right to the heart of one of the most basic areas of confusion that programmers coming from garbage collected environments to ones with manual memory management have.
They need to understand that they have NOT been working in an environment without pointers, as they are often told to believe, but one in which nearly everything is a pointer. Understanding this is fundamental to understanding these differences and a 10,000 word essay about C++ allocation policies will not make it any clearer without dealing with that first.
I agree with grandparent that understanding what a pointer is and that almost everything in a Java program is a pointer it's critical for a Java programmer.
EDIT: After thinking about it a little, most of the Java people I know have at least some embedded or native background. This could be a reason. I don't know what the market over all is like.
But yes, a java programmer with embedded or native background would have a better understanding of this than people who learned Java first, which is what I'm really addressing here. And in the OP on SE you can clearly see that this is a big part of that person's confusion.
I can't find any information on that, do you have a link on that subject?
They learned programming by reading blogs and pirated PDF files on BitTorrent. Of course they don't got a level of understanding most hackers here have.
You want a good programmer you need 15+ years of experience plus a good understanding of computer science, recent high school and college dropouts don't have that.
You hire a cheaper labor source, you won't get that level of quality a more expensive labor source will give you and you get what you pay for!
https://stackoverflow.com/questions/6500313/c-why-should-new...
For example, let's say you have a class that news up an object in its constructor. Presumably, the corresponding delete lives in the destructor. But if that constructor throws an exception, the destructor will never be called. If it throws the exception after the "new," then you have a memory leak.
So basically, you need a class whose only job is to manage a single pointer. You could certainly roll your own smart pointer, but it would have to work pretty much exactly like one of the ones in the standard library.
First, auto or scoped pointer gets you a stack discipline. If your objects weren't very big, you might as well create them on the stack itself. More efficient and suitable for multithreading. If the lifetime does not follow the lexical stack then you are out of luck with this style of RAII.
Next, reference counted pointers: Cycles are clearly a problem. The traditional mantra is: use weak pointers to break cycles, but then you are back to error prone manual management (of cycles). If I am to be trusted with using weak pointers correctly, I wouldn't be too bad with manual memory management either. Pure functional languages with eager semantics do not allow cycles, so are ref counts a good idea in such cases ?
Although, many do not think about it that way, reference counted system is a _garbage_collector_. Just a particularly simple one. Just because one understands how it works, does not disqualify it from being a garbage collection system. It is just not a very efficient garbage collector for cases where running time is sensitive to cache locality, which is true fairly often.
I am quite excited about Rust's regions. I dont think programming with regions is easy and you would want to have a garbage collector anyway. I hope this style of programming sees more mainstream visibility. Something should come out of all the MLton work on this. EDIT Indeed meant MLKit but it draws enough from MLton that I thought HNers would be able to relate.
There is also D's scoped guards, but I am not yet familiar with what they do.
I agree and I've been wanting to emphasize this too for a while.
I think it would help Rusts adoption a lot if it would get a good garbage collector while it's still young. Otherwise I think a lot of programmers will give up after stumbling around with borrow-checker errors when doing some things that are pretty trivial in other languages.
If we had a garbage collector, we could only worry about regions in the hot spots, that would ease many people's way into the language a lot, IMO.
Exactly. An awful one.
(I mostly write C + Obj-C)
Consider a C example:
int f()
{
int ret = -1;
handle * a = acquire_handle(0);
if (a == NULL) goto fail1;
handle * b = acquire_handle(1);
if (b == NULL) goto fail2;
handle * c = acquire_handle(2);
if (c == NULL) goto fail3;
// use a, b, c
ret = 0;
release_handle(c);
fail3:
release_handle(b);
fail2:
release_handle(a);
fail1:
return ret;
}
Consider a C# example: void f()
{
using (handle a = new handle(0))
using (handle b = new handle(1))
using (handle c = new handle(2))
{
// use a, b, c
}
}
Now a C++ example using RAII: void f()
{
handle a{0};
handle b{1};
handle c{2};
// use a, b, c
}
These examples are mostly equivalent (Although the C#/C++ assume exceptions instead of error codes).The C#/C++ examples are far more structured and less error prone than the C example.
The advantage of C++'s RAII over C#'s using statement is that cleanup is tied to the object rather than a statement. This means that RAII is both composable and non-leaky as an abstraction. You cannot forget to destruct an object in C++, and you don't have to care that its destructor frees resources. When you have an IDisposable member in C# you must manually mark your class as IDisposable and then implement the Dispose method yourself. Clients must also be aware that your class is IDisposable in order to use it correctly.
using (handle a = new handle(0))
using (handle b = new handle(1))
using (handle c = new handle(2)) {
// use a, b, c
} handle a, b, c;
if (!aquire_handle(&a, 0)) goto fail1;
if (!aquire_handle(&b, 1)) goto fail2;
if (!aquire_handle(&c, 2)) goto fail3;edit 2: I judge a language in part by seeing if they actually can define nested / chained exceptions well. If they don't, they're probably not too serious about exception handling...
What's an example of a language you like that does exceptions in a better way?
func f() error {
var a, b, c *handle
var err error
if a, err = acquireHandle(0); err != nil {
return err
}
defer a.Close()
if a, err = acquireHandle(1); err != nil {
return err
}
defer b.Close()
if a, err = acquireHandle(2); err != nil {
return err
}
defer c.Close()
//use a, b, c
return nil
}But crucially, their destructor is called (and any destructors of their member variables, etc.) The destructor might perform cleanup work beyond freeing up memory. For example, std::istream will close the file handle when it goes out of scope, and boost::lock_guard will release the lock.
RAII isn't rocket science, but there are some advantages over plain C where all cleanup has to be explicit and it's fairly easy to get resource deallocation wrong if you don't know what you're doing. And as the Wikipedia article says, RAII is vital in writing exception-safe code in C++ if you don't want to litter try/catch blocks all over your code.
http://en.wikipedia.org/wiki/Resource_Acquisition_Is_Initial...
And the destructor, if any, is called. That means you can bundle automatic cleanup action in the destructor, no need for goto: cleanup, @try/@finally or some other sort of "manual" cleanup, the cleanup is implicitly set up by, well, the setup.
The ability itself is by no means unique to C++ (even amongst oldies, Smalltalk has BlockClosure#ensure: and Common Lisp has unwind-protect) but a surprising number of languages still don't have such a capability, and it's a pretty neat consequence of C++'s memory model.
Right, that's implied by a C++ object being deallocated. I understand how it works - it's just that it's really obvious if you know anything at all about how the stack works (and C++ destructors).
Which does not change it being an elegant solution to the problem of resource scoping does it?
Also the semantics of C++ destructor (and their relation to stack deallocation) had to be defined to get RAII, and it was, back in the very early 80s when the idea of resource scoping was not exactly well known.
mutex.lock();
doStuff(); /*throws an exception, mutex is never unlocked*/
mutex.unlock();
ScopedLock lock(mutex);
doStuff(); /*mutex unlocked by destructor in all cases*/
It guarantees that resources are freed no matter how the scope exits.That's all it is.
But, it guarantees that a given piece of code (an object's destructor) is always executed when execution leaves the current scope, either through normal execution, by calling `return`, or by throwing an exception.
In fact, RAII is the thing that allows exceptions to be remotely usable in C++; the lack of RAII in Obj-C is the reason why exceptions are not common in Obj-C.
It's used for regular memory management, but it's also used for managing access to other resources, such as files, mutexes, etc. E.g., you can use it ensure that a file handle is automatically closed when you leave scope.
Beyond pointers, it applies to many things that have a "C-style" API. Without RAII, anything that needs to be explicitly cleaned up needs to be monitored. For example, if you declare a pthread mutex, it doesn't help you that the mutex variable itself goes out of scope, because it's just a pointer and that will not clean up the actual mutex.
And as people have said, without RAII it's impossible to write exception-safe code.
Assuming that's hyperbole, I agree with the sentiment. It's possible to write exception safe code with try & catch - it's just almost as ugly as checking exit statuses and easier to miss something.
In some ways it is just another of the myriad of implicit behaviours in C++ that make it hard to work with, though.
With this approach, you can still allocate objects on the stack - you then take their address and pass that to a subroutine.
Qt also has used its own smart pointers for a while but these generally are declared within some container class, so the idiom basically allows you to do allocation entirely within containers and so never use the new operator directly.
Now, there may be situations where you have a complex chain of multiple connections that don't fit to an existing container. The sloppy way then is to use new and the good way to write a custom container. The idiom can also when dealing external libraries that allocate memory directly or somehow demand you use the new operator.
They don't even bother to teach pointers, the stack, or heap. It just confuses the students they claim. Also teach students to store the value of PI into an Integer. Use DRJava and Java 6 and some bloated JAR library that makes Windows crash.
When I studied computer science in 1986, the very first things we learned where how memory and binary worked, plus what a pointer was and why it should be used and how to manage memory so it would not crash and lock up. We learned how to debug as well.
Most comp sci graduates that I talk to know almost nothing of how a pointer works, or the stack or heap, and binary might as well be Tagalog to them.
I think that over the years as the demand for IT workers increased, they relaxed the standards they used in teaching computer science and programming.
Any good MOOC should teach:
Pointers
The Stack
The Heap
Binary
Hexadecimal
How to debug code
Assembly Language instructions the code gets converted into and how to debug that
Allocating on the heap means you have to delete it yourself in C++.
It's pretty staightforward, no?
To beat the subject completely to death:
Pointers, References and Values
Passing Parameters, Returning Results, and Storing Member Variables with Musings on Good C++ Style
http://www.warplife.com/tips/code/c++/memory-management/para...