D Language
범위 경비원
수색…
통사론
- scope (exit) - 명령문은 현재 블록이 어떻게 종료되었는지에 관계없이 호출됩니다.
- scope (성공) - 현재 블록이 정상적으로 종료되었을 때 명령문이 호출됩니다.
- scope (failure) - 현재 블록이 예외 발생을 통해 종료 될 때 문이 호출됩니다.
비고
스코프 가드를 사용하면 코드를 훨씬 깔끔하게 정리할 수 있으며 리소스 할당 및 코드 정리가 가능합니다. 이 작은 도우미는 특정 정리 코드가 런타임에서 실제로 취해진 경로와는 독립적으로 항상 호출되도록하기 때문에 안전성을 향상시킵니다.
D 스코프 기능은 C ++에서 사용 된 RAII 관용구를 효과적으로 대체합니다.이 관용구는 종종 특수 자원에 대한 특수 스코프 가드 객체로 연결됩니다.
스코프 가드는 정의 된 역순으로 호출됩니다.
서로 옆에 할당 및 정리 코드 배치
스코프 가드는 현재 블록이 남아있는 경우 특정 조건에서 명령문을 실행할 수있게합니다.
import core.stdc.stdlib;
void main() {
int* p = cast(int*)malloc(int.sizeof);
scope(exit) free(p);
}
여러 중첩 스코프
import std.stdio;
void main() {
writeln("<html>");
scope(exit) writeln("</html>");
{
writeln("\t<head>");
scope(exit) writeln("\t</head>");
"\t\t<title>%s</title>".writefln("Hello");
} // the scope(exit) on the previous line is executed here
writeln("\t<body>");
scope(exit) writeln("\t</body>");
writeln("\t\t<h1>Hello World!</h1>");
}
인쇄물
<html>
<head>
<title>Hello</title>
</head>
<body>
<h1>Hello World!</h1>
</body>
</html>
Modified text is an extract of the original Stack Overflow Documentation
아래 라이선스 CC BY-SA 3.0
와 제휴하지 않음 Stack Overflow