As a long-time C# programmer, I have recently come to learn more about the advantages of Resource Acquisition Is Initialization (RAII). In particular, I have discovered that the C# idiom:
using (myvar dbConn = new DbConnection(connStr)) {
// do stuff with dbConn
}
has the C++ equivalent:
{
DbConnection dbConn(connStr);
// do stuff with dbConn
}
meaning that remembering to enclose the use of resources like DbConnection
in a using
block is unnecessary in C++ ! This seems to a major advantage of C++. This is even more convincing when you consider a class that has an instance member of type DbConnection
, for example
class Foo {
DbConnection dbConn;
// ...
}
In C# I would need to have Foo implement IDisposable
as such:
class Foo : IDisposable {
DbConnection dbConn;
public void Dispose()
{
dbConn.Dispose();
}
}
and what's worse, every user of Foo
would need to remember to enclose Foo
in a using
block, like:
using (var foo = new Foo()) {
// do stuff with "foo"
}
Now looking at C# and its Java roots I am wondering... did the developers of Java fully appreciate what they were giving up when they abandoned the stack in favor of the heap, thus abandoning RAII?
(Similarly, did Stroustrup fully appreciate the significance of RAII?)