I am actually making a simple C++ SFML game and I want to learn much more into C++ programming.
Now I am using shared_ptr to manage resources. I have some question about shared_ptrs when creating a new resource like:
shared_ptr< Resource > resource( new Resource( World::LEVEL ) );
According to boost shared_ptr< class Y>( Y * p ) throws bad_alloc. I dunno if std::tr1 does the same. And I do not know if I should worry about putting shared_ptr inside a try/catch block to check if bad_alloc is thrown. Is this a good programming practice?
Per the C++ 2011 standard, §20.7.2.2.1 ¶6:
template<class Y> explicit shared_ptr(Y* p);
Throws:
bad_alloc
, or an implementation-defined exception when a resource other than memory could not be obtained.
You catch exceptions when you know how to handle them. If you're going to handle a out-of-memory exception and have code to do so, then by all means, put it in a try-catch. If you're not writing mission-critical code and don't expect to be operating on the edge of system memory constraints, it's likely not necessary. Note that pretty much every line of code you write can throw exceptions once your system is out of memory.
It's important to note that on modern hardware/operating systems, "out of memory" doesn't mean that you've exceeded the physical memory constraints - you can have only 128MiB of memory and not get an error even when you use 10 times that, and you can have 8GiB of physical memory and get that error when you've only used half that much. This refers to the memory space available to your application, which the OS will page to disk if necessary (and assuming available disk space).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With