Время жизни объекта в С/С++
От: Lorenzo_LAMAS  
Дата: 28.01.08 09:35
Оценка:
Сразу оговорюсь, речь пойдет об объектах встроенных типов (int), поэтому, пожалуйста, не надо ничего про деструкторы в С++ писать.

В С (6.2.4):

For such an object that does not have a variable length array type, its lifetime extends
from entry into the block with which it is associated until execution of that block ends in
any way. (Entering an enclosed block or calling a function suspends, but does not end,
execution of the current block.)
If the block is entered recursively, a new instance of the
object is created each time. The initial value of the object is indeterminate. If an
initialization is specified for the object, it is performed each time the declaration is
reached in the execution of the block; otherwise, the value becomes indeterminate each
time the declaration is reached.


Есть:

#include <stdio.h>

_Bool first = 1;
int main()
{
   int * p = 0;
   if(!first)
   {
   label:
      int k = 0;
      printf("Value %d\n", *p);
   }
   int i = 10;
   if(first)
   {
      first = 0;
      p = &i;
      goto label;
   }
}


указатель p должен быть валиден, т.к. время жизни i — это весь блок и после goto оно еще не закончилось, а значит:

6.2.4/2
The lifetime of an object is the portion of program execution during which storage is
guaranteed to be reserved for it
.


таким образом, в данном случае компилятор не может, стремясь экономить место, размещать объекты с разным временем жизни по одному и тому же адресу: разместить как-то k, а потом, т.к. его время жизни закончилось с выходом из блока
разместить там же i?

Как быть с этим примером в С++? Там нет таких формулировок, как в С, говорится, что

3.8/1
The lifetime of an object is a runtime property of the object. The lifetime of an object of type T begins
when:
storage with the proper alignment and size for type T is obtained, and
— if T is a class type with a non-trivial constructor (12.1), the constructor call has completed.
The lifetime of an object of type T ends when:
— if T is a class type with a non-trivial destructor (12.4), the destructor call starts, or
the storage which the object occupies is reused or released.

3.8/2

[Note: the lifetime of an array object or of an object of POD type (3.9) starts as soon as storage with proper
size and alignment is obtained, and its lifetime ends when the storage which the array or object occupies is
reused or released. 12.6.2 describes the lifetime of base and member subobjects. ]

3.7.2/1

Local objects explicitly declared auto or register or not explicitly declared static or extern have
automatic storage duration. The storage for these objects lasts until the block in which they are created
exits.

Of course, the code must be complete enough to compile and link.
 
Подождите ...
Wait...
Пока на собственное сообщение не было ответов, его можно удалить.