Difference between revisions of "Nil/ru"

From Lazarus wiki
Jump to navigationJump to search
Line 7: Line 7:
 
__TOC__
 
__TOC__
  
== assignment compatibility ==
+
== Совместимость присвоения ==
 
<syntaxhighlight lang="pascal" enclose="none">nil</syntaxhighlight> can be of course [[Becomes|assigned]] to a [[Pointer|<syntaxhighlight lang="pascal" enclose="none">pointer</syntaxhighlight>]] variable, but also to other types, which are in fact pointers, but their usage is more convenient.
 
<syntaxhighlight lang="pascal" enclose="none">nil</syntaxhighlight> can be of course [[Becomes|assigned]] to a [[Pointer|<syntaxhighlight lang="pascal" enclose="none">pointer</syntaxhighlight>]] variable, but also to other types, which are in fact pointers, but their usage is more convenient.
 
For instance [[Dynamic array|dynamic arrays]] or [[Class|classes]]:
 
For instance [[Dynamic array|dynamic arrays]] or [[Class|classes]]:
 +
 +
Конечно, <syntaxhighlight lang="pascal" enclose="none">nil</syntaxhighlight> может быть [[Becomes/ru|присвоен]] переменной [[Pointer/ru|<syntaxhighlight lang="pascal" enclose="none">pointer</syntaxhighlight>]], но также и другим типам, которые на самом деле являются указателями, но их использование более удобно. Например, [[Dynamic_array/ru|динамические массивы]] или [[Class/ru|классы]]:
 
<syntaxhighlight lang="pascal" line highlight="10,12,14,16,18">
 
<syntaxhighlight lang="pascal" line highlight="10,12,14,16,18">
 
program nilDemo(input, output, stderr);
 
program nilDemo(input, output, stderr);
Line 19: Line 21:
 
obj: TObject;
 
obj: TObject;
 
begin
 
begin
// point to nothing
+
// указываем в никуда
 
loc := nil;
 
loc := nil;
// clears dynamic array
+
// очищаем динамический массив
 
chk := nil;
 
chk := nil;
// empty string
+
// очищаем строку
 
msg := nil;
 
msg := nil;
// procedural variable not referencing any procedure
+
// процедурная переменная не ссылается ни на одну процедуру
 
prc := nil;
 
prc := nil;
// loses reference to object
+
// теряем ссылку на объект
 
obj := nil;
 
obj := nil;
 
end.
 
end.
 
</syntaxhighlight>
 
</syntaxhighlight>
Note, assigning <syntaxhighlight lang="pascal" enclose="none">nil</syntaxhighlight> to a dynamic array is virtually equivalent to the procedure invocation <syntaxhighlight lang="pascal" enclose="none">setLength(dynamicArrayVariable, 0)</syntaxhighlight>.
+
Обратите внимание, что присвоение <syntaxhighlight lang="pascal" enclose="none">nil</syntaxhighlight> динамическому массиву практически эквивалентно вызову процедуры <syntaxhighlight lang="pascal" enclose="none">setLength(dynamicArrayVariable, 0)</syntaxhighlight>. Значения массива теряются, если счетчик ссылок <tt>dynamicArrayVariable</tt> достигает нуля. Однако не существует сопоставимого механизма для других типов, например, присвоение <syntaxhighlight lang="pascal" enclose="none">nil</syntaxhighlight> переменной <syntaxhighlight lang="pascal" enclose="none">class</syntaxhighlight>'а или <syntaxhighlight lang="pascal" enclose="none">pointer</syntaxhighlight> ''не'' освободит (т.е. де-аллокирует) память, которая, возможно, была занята ссылочной структурой.
The values of the array are lost, if the reference count of <syntaxhighlight lang="pascal" enclose="none">dynamicArrayVariable</syntaxhighlight> has hit zero.
 
However, there is no comparable mechanism for other types, e.g. assigning <syntaxhighlight lang="pascal" enclose="none">nil</syntaxhighlight> to a <syntaxhighlight lang="pascal" enclose="none">class</syntaxhighlight> or <syntaxhighlight lang="pascal" enclose="none">pointer</syntaxhighlight> variable ''will not'' release (i.e. de-allocate) the memory that is possibly been occupied by the referenced structure.
 
  
 
== application ==
 
== application ==

Revision as of 22:03, 9 May 2019

Deutsch (de) English (en) suomi (fi) français (fr) русский (ru) 中文(中国大陆)‎ (zh_CN)

Зарезервированное слово nil представляет собой специальное значение переменной-указателя, не указывающей ни на что конкретное. В FPC это реализовано как pointer(0) (числовое значение 0), однако программист не должен использовать этот факт. На других языках программирования, например на C, кто-то пишет null. Термины “null pointer” или “nil pointer” используются взаимозаменяемо, даже среди программистов на Паскале.

Есть два популярных объяснения этимологии nil. Кто-то говорит: nil означает латинское слово «nihil», означающее «ничего». Другой предполагает, что NIL - это английская аббревиатура, обозначающая “not in list” (нет в списке). Может быть, поскольку немецкое слово «Null» обозначает цифру «ноль», чтобы избежать путаницы или для различия между понятием и значением, было выбрано слово nil. Во всяком случае, это не имеет никакой разницы при программировании.

Совместимость присвоения

nil can be of course assigned to a pointer variable, but also to other types, which are in fact pointers, but their usage is more convenient. For instance dynamic arrays or classes:

Конечно, nil может быть присвоен переменной pointer, но также и другим типам, которые на самом деле являются указателями, но их использование более удобно. Например, динамические массивы или классы:

 1program nilDemo(input, output, stderr);
 2var
 3	loc: pointer;
 4	chk: array of boolean;
 5	msg: PChar;
 6	prc: TProcedure;
 7	obj: TObject;
 8begin
 9	// указываем в никуда
10	loc := nil;
11	// очищаем динамический массив
12	chk := nil;
13	// очищаем строку
14	msg := nil;
15	// процедурная переменная не ссылается ни на одну процедуру
16	prc := nil;
17	// теряем ссылку на объект
18	obj := nil;
19end.

Обратите внимание, что присвоение nil динамическому массиву практически эквивалентно вызову процедуры setLength(dynamicArrayVariable, 0). Значения массива теряются, если счетчик ссылок dynamicArrayVariable достигает нуля. Однако не существует сопоставимого механизма для других типов, например, присвоение nil переменной class'а или pointer не освободит (т.е. де-аллокирует) память, которая, возможно, была занята ссылочной структурой.

application

In a Pascal's manner you usually do not write expressions like pointerVariable = nil but use more explanatory identifiers. The routine system.assigned will be replaced by the exact same expression, but conceals the fact a variable is (implemented as) a pointer. So its usage is optional.

The routine SysUtils.FreeAndNil will call a class's free routine and assign nil to the handed pointer (variable of type class). Although it is a good idea, to clear pointers which do not point to valid objects anymore, this can make debugging more difficult, since there is no pointer available, pointing to the address a certain object used to be.

see also