LoginSignup
11
12

More than 5 years have passed since last update.

スコープでリソースを破棄するいろいろなやりかた

Last updated at Posted at 2014-01-14

RAII(C++)

wikipediaから参照。デストラクタが自動変数の破棄によってよびだされて、そのときにリソースのcloseを行う。closeのAPIが例外を出さないことが前提。perlのguard系モジュールとかもそう。

void functionA()
{
    LogFile log("Output log of functionA");

    log.write("fun Step succeeded");

    // ... logを使い続ける ...
    // 例外が送出されようと、関数からreturnが行われようと確実にlogのファイルハンドルは閉じられる。
}

with句(python)

昔は無かったけど、増えた。

with open("hello.txt") as f:
    for line in f:
        print line

proc受け取り(ruby)

closureを受け取り、その関数の実行前後でリソースの確保と破棄を行う。

open("foo.csv") {|file|
  while l = file.gets
    lines += 1
    fields += l.split(',').size
  end
}

using句(C#)

c#はwith見たいのがあるよ。

// Disposeメソッドを実装しておけば、using抜けた後に使える

using (StreamWriter writer = 
                new StreamWriter("memo.txt", false, Encoding.UTF8))
{
    writer.Write("テキスト");
}

scope(D-lang)

scopeのあとの関数が、脱出時に評価される。

void abc()
{
    Mutex m = new Mutex;

    lock(m);    // mutexをロック
    scope(exit) unlock(m);  // スコープ終了時にアンロック

    foo();  // 処理を行う
}

defer(go-lang)

scopeと似てる

    f, err := os.Open(filename)
    if err != nil {
        return "", err
    }
    defer f.Close()  // f.Closeは、完了時に実行される

try-with-resources構文(java)

AutoCloseableのInterfaceを実装しているものを閉じてくれる。
(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)

オブジェクトのロックの獲得管理が、構文でできる。

class MyObject {
  int val;

  MyObject(int val) {
    this.val = val;
  }

  synchronized void setVal(int val) {
    this.val = val;
  }

  synchronized int getVal() {
    return val;
  }
}

とりあえず、なんか思い出したら追記します。

11
12
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
12