Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it safe to use unique_ptr in an Exception class

Is it safe to use unique_ptr? When I use cout in destructor, sometimes it called more then one time. - so it make copy time-to-time. if it take two copy from one object - data can be lost..

#include <memory>

class MyException
{
    std::unique_ptr<Type> data;

    MyException();
    ~MyException() {cout<<"test"<<endl;}

    MyException(MyException ex&);
};

int main()
{
    try
    {
        try
        {
            throw MyException();
        }
        catch (const MyException& ex)
        {
            throw;
            //or?
            throw ex; //will be copied?
        }
    return 0;
    }
    catch(const MyException/*& will be missed. will ex be copied?*/ ex)
    {
        throw; //wich ex will be re-throw, copy or original?
        //or?
        throw ex; //will be copied?
    }
}

Can I be sure, that data will not be lost between re-throws? And is this good practic to use ptr inside exception to collect error info from different levels?

Also, can MyException.data be lost after:

std::exception_ptr ex =  std::current_exception();
std::rethrow_exception(ex);
like image 240
Darida Avatar asked Dec 20 '25 06:12

Darida


1 Answers

As you discovered, you should always say throw; when you want to re-throw an exception, not not throw ex;. Indeed, throw ex; will copy (and slice, if ex is a reference to a base class!).

So, always catch by reference, and always re-throw without naming the exception.

like image 181
John Zwinck Avatar answered Dec 22 '25 21:12

John Zwinck



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!