Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can this method ever throw an exception?

Consider:

template <typename T>
struct S
{
    auto Value() const
    {
        return value;
    }

    T value;
};

Can Value() ever throw an exception? Why or why not? If not, is it safe to mark this method as noexcept ?

What I fundamentally don’t understand is whether return value; is something that can ever throw an exception.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Value() might throw an exception and therefore you should not mark it as noexcept.

This might happen since Value() returns a T object by value.
This means a copy will be made and the copy constructor of T might throw. The compiler will generate the copy istructions in the method body.

Copy-ellision is not relevant because value is a member, not a local or a temporary.
But even if was relevant, it does not change that.
The content of the value member would anyway to be copied (or moved) into the target object that called the method. This would be done by way of executing the relevant constructor of T – copy or move – or assignment operator which might throw.

It does not matter if the return value is actually assigned to a variable, as you can see in the demo below.

Demo – courtesy of @joergbrech.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading