RAII(C++)
See from wikipedia. The destructor is called by destroying the automatic variable, and the resource is closed at that time. It is assumed that the close API does not raise an exception. Like perl's guard module.
void functionA()
{
LogFile log("Output log of functionA");
log.write("fun Step succeeded");
// ...Continue to use log...
//Whether an exception is thrown or a function returns, the log file handle is reliably closed.
}
It didn't exist in the past, but it has increased.
with open("hello.txt") as f:
for line in f:
print line
Receives closure and allocates and destroys resources before and after execution of the function.
open("foo.csv") {|file|
while l = file.gets
lines += 1
fields += l.split(',').size
end
}
I want to see c # with.
//If you implement the Dispose method, you can use it after exiting using
using (StreamWriter writer =
new StreamWriter("memo.txt", false, Encoding.UTF8))
{
writer.Write("text");
}
scope(D-lang)
The function after scope is evaluated on escape.
void abc()
{
Mutex m = new Mutex;
lock(m); //Lock mutex
scope(exit) unlock(m); //Unlock at end of scope
foo(); //Do the processing
}
defer(go-lang)
Similar to scope
f, err := os.Open(filename)
if err != nil {
return "", err
}
defer f.Close() // f.Close is executed on completion
It closes the one that implements AutoCloseable Interface. (Thanks to tsuyoshi_cho)
public static void main(String[] args) {
try (AutoCloseable imp = new AutoCloseableImpl()) { // New!
System.out.println("hoge");
} catch(Exception e) {
System.out.println("catch:" + e);
} finally {
System.out.println("finally");
}
}
synchronized(Java) You can manage the acquisition of locks on objects with syntax.
class MyObject {
int val;
MyObject(int val) {
this.val = val;
}
synchronized void setVal(int val) {
this.val = val;
}
synchronized int getVal() {
return val;
}
}
For the time being, I will add it if I remember something.
Recommended Posts