Object lifetime
Encyclopedia : O : OB : OBJ : Object lifetime
In computer science, the object lifetime (or life cycle) of an object in object-oriented programming is the time between an object's creation (also known as instantiation or construction) till the object is no longer used, and is destructed or freed.
In object-oriented programming (OOP), the meaning of creating objects is far more subtle than simple allocating of spaces for variables. First, this is due to the fact that, in the OOP paradigm, the lifetime of each object tends to vary more widely than in the case in conventional programming. There are a lot of subtle questions, including whether the object be considered alive in the process of creation, and concerning the order of calling initializing code. In some sense, the creation can happen before the beginning of the program when objects are placed in a global scope.
Creating objects
In a typical case, the process is as follows:- calculate the size of an object - the size is mostly the same as that of the class but can vary. When the object in question is not derived from a class, but from a prototype instead, the size of an object is usually that of the internal data structure (a hash for instance) that holds its slots.
- allocation - allocating memory space with the size of an object plus the growth later, if possible to know in advance
- binding methods - this is usually either left to the class of the object, or is resolved at dispatch time, but nevertheless it is possible that some object models bind methods at creation time
- calling an initializing code (namely, constructor) of superclass
- calling an initializing code of class being created
It is a complex problem to create each object as an element of an array. Some languages (e.g. C++) leave this to programmers.
Handling exceptions in the midst of creation of an object is particularly problematic because usually the implementation of throwing exceptions relies on valid object states. For instance, there is no way to allocate a new space for an exception object when the allocation of an object failed before that due to a lack of free space on the memory. Due to this, implementations of OO languages should provide mechanisms to allow raising exceptions even when there is short supply of resources, and programmers or the type system should ensure that their code is exception-safe. Note that propagating an exception is likely to free resources (rather than allocate them). However, in object oriented programming, object construction may always fail, because constructing an object should establish the class invariants, which are often not valid for every combination of constructor arguments. Thus, constructors can always raise exceptions.
The abstract factory pattern is a way to decouple a particular implementation of an object from code for the creation of such an object.
Creation methods
The way to create objects varies across languages. In some class-based languages, a special method known as a constructor, is responsible for validating the state of an object. Just like ordinary methods, constructors can be overloaded in order to make it so that an object can be created with different attributes specified. Also, the constructor is the only place to set the state of immutable objects. A copy constructor is a constructor which takes a (single) parameter of an existing object of the same type as the constructor's class, and returns a copy of the object sent as a parameter.Other programming languages, such as Objective-C, have class methods, which can include constructor-type methods, but are not restricted to merely instantiating objects.
C++ and Java have been criticized for not providing named constructors. This can be problematic, for instance, when a programmer wants to provide ways to create a point object either from cartesian coordinate or from the polar coordinate--because both coordinates would be represented by two integers. Objective-C can circumvent this problem, in that the programmer can create a Point class, with initialization methods, for example, +newPointWithX:andY:, and +newPointWithR:andTheta:.
A constructor can also refer to a function which is used to create a value of a tagged union, particularly in functional languages.
Destroying objects
It is generally the case that after an object is used, it is removed from memory to make room for other programs or objects to take that object's place. In order for this to happen, a destruction method is called upon that object. Destroying an object will cause any references to the object to become invalid.A destructor is a method called when an instance of a class is deleted, before the memory is deallocated. Note that in C++, a destructor can not be overloaded like a constructor can. It has to have no arguments. A destructor does not need to maintain class invariants. In certain garbage-collect languages, finalizers are used instead of destructors since garbage-collection may be non-deterministic in these languages. An example of this is Ruby.
In a garbage collecting language, objects are destroyed when they can no longer be reached by the running code. Examples of this are Python and Java. Python has destructors, and they are optional.
Examples
class Foo
;
Foo::Foo(int x)
Foo::Foo(int x, int y)
Foo::Foo(const Foo &old)
Foo::~Foo()
int main()
class Foo
public Foo(int x, int y)
public Foo(Foo old)
public static void main(String[] args)
}
#import
@interface Point : Object
//These are the class methods; we have declared two constructors
+ (Point *) newWithX: (double) andY: (double);
+ (Point *) newWithR: (double) andTheta: (double);
//Instance methods
- (Point *) setFirstCoord: (double);
- (Point *) setSecondCoord: (double);
/* Since Point is a subclass of the generic Object
* class, we already gain generic allocation and initialization
* methods, +alloc and -init. For our specific constructors
* we can make these from these methods we have
* inherited.
*/
@end
@implementation Point
- (Point *) setFirstCoord: (double) new_val
- (Point *) setSecondCoord: (double) new_val
+ (Point *) newWithX: (double) x_val andY: (double) y_val
+ (Point *) newWithR: (double) r_val andTheta: (double) theta_val
@end
int
main(void)
class Socket:
def (self, remote_host):
self.connection = connectTo(remote_host)
def send(self):
# send data
def recv(self):
# receive data
def f():
s = Socket('example.com')
s.send('blah')
return s.recv()
Socket will be closed at the next garbage collection round, as all references to it have been lost.See also
- Resource Acquisition Is Initialization (RAII), an approach to managing object lifetime
From Wikipedia, the Free Encyclopedia. Original article here. Support Wikipedia by contributing or donating.
All text is available under the terms of the GNU Free Documentation License See Wikipedia Copyrights for details.
Foo::Foo(int x)
Foo::Foo(int x, int y)
Foo::Foo(const Foo &old)
Foo::~Foo()
int main()
class Foo
public Foo(int x, int y)
public Foo(Foo old)
public static void main(String[] args)}
#import
@interface Point : Object
//These are the class methods; we have declared two constructors
+ (Point *) newWithX: (double) andY: (double);
+ (Point *) newWithR: (double) andTheta: (double);
//Instance methods
- (Point *) setFirstCoord: (double);
- (Point *) setSecondCoord: (double);
/* Since Point is a subclass of the generic Object
* class, we already gain generic allocation and initialization
* methods, +alloc and -init. For our specific constructors
* we can make these from these methods we have
* inherited.
*/
@end
@implementation Point
- (Point *) setFirstCoord: (double) new_val
- (Point *) setSecondCoord: (double) new_val
+ (Point *) newWithX: (double) x_val andY: (double) y_val
+ (Point *) newWithR: (double) r_val andTheta: (double) theta_val
@end
int
main(void)
class Socket:
def (self, remote_host):
self.connection = connectTo(remote_host)
def send(self):
# send data
def recv(self):
# receive data
def f():
s = Socket('example.com')
s.send('blah')
return s.recv()
Socket will be closed at the next garbage collection round, as all references to it have been lost.See also
- Resource Acquisition Is Initialization (RAII), an approach to managing object lifetime
From Wikipedia, the Free Encyclopedia. Original article here. Support Wikipedia by contributing or donating.
All text is available under the terms of the GNU Free Documentation License See Wikipedia Copyrights for details.
@interface Point : Object
//These are the class methods; we have declared two constructors + (Point *) newWithX: (double) andY: (double); + (Point *) newWithR: (double) andTheta: (double);
//Instance methods - (Point *) setFirstCoord: (double); - (Point *) setSecondCoord: (double);
/* Since Point is a subclass of the generic Object * class, we already gain generic allocation and initialization * methods, +alloc and -init. For our specific constructors * we can make these from these methods we have * inherited. */ @end
@implementation Point
- (Point *) setFirstCoord: (double) new_val
- (Point *) setSecondCoord: (double) new_val
+ (Point *) newWithX: (double) x_val andY: (double) y_val
+ (Point *) newWithR: (double) r_val andTheta: (double) theta_val
@end
int main(void)
class Socket: def (self, remote_host): self.connection = connectTo(remote_host)Socket will be closed at the next garbage collection round, as all references to it have been lost.def send(self): # send data
def recv(self): # receive data
def f(): s = Socket('example.com') s.send('blah') return s.recv()
See also
- Resource Acquisition Is Initialization (RAII), an approach to managing object lifetime
From Wikipedia, the Free Encyclopedia. Original article here. Support Wikipedia by contributing or donating.
All text is available under the terms of the GNU Free Documentation License See Wikipedia Copyrights for details.
