C++ was designed to take care of allocating memory and initializing that memory when an object is declared and destructing and deallocating memory when the object goes out of scope if it was created on the stack. It's mechanisms for doing this are the constructors and destructor of a class. The constructor is called to do all the initialization of the object, while the destructor handles cleanup.
These functions are called for you by the compiler as sort of automatic lifetime management.
The copy assignment operator ( operator= ) is a function that can be overloaded in cases where things need to be handled before assigning more trivial data from one object to another, such as copying file data or image data before copying the simpler file size or image dimensions. The best part is, this function is called when you do your normal a = b, so no need to b = a.clone() or whatever ( with the exception of inheritance ).
So with these mechanisms in place, why do people feel the need to use Init() and Release() functions which have to be called manually?
Compare
Code: Select all
// Using constructor/destructor
int main()
{
try
{
MyClass a( 420 );
a.Run();
a = MyClass( 42 );
a.Run();
}
catch( const std::exception& e )
{
std::cout << e.what << '\n';
return -1;
}
return 0;
}
Code: Select all
int main()
{
MyClass a;
if( !a.Init( 420 ) )
{
a.Release();
std::cout << "Unkown error." << '\n';
return -1;
}
a.Run();
MyClass copy;
if( !copy.Init( 42 ) )
{
a.Release();
copy.Release();
std::cout << "Unknown error, unable to copy." << '\n';
return -1;
}
a = copy;
a.Run();
a.Release();
copy.Release();
return 0;
}
In TSI ( two stage initialization ), you'd have to check that the 'copy' object was also successful, so you'd have to initialize it and release it manually.
So what brought this up?
The other day I got on YT and a video series was suggested to me, "C++ 3D Game Tutorial". It is a tutorial series and the author uses TSI.
Now, the author of the series seems to be a very nice person, so I'm not going to push too hard on the guy, after all he is delivering content I'm sure will help a few people break into making 3D games and I'm not going to hijack his channel in hopes people check out chili's content either. ( though I really wanted to hehe ).
Anyway, the long and short of it is, is the damn constructors and destructor for what they were meant.
Again, if anyone can explain to me why one would choose to use two stage initialization over constructors, please feel free.