0

MSVC 2019 gives a hint

C26439: This kind of function may not throw. Declare it 'noexcept' (f.6)

It refers to C++ Core Guidelines f.6: If your function may not throw, declare it noexcept. However, I am not sure whether all members of my class never throw exceptions when moved. In particular, there is OpenCV's Mat, which doesn't have noexcept specifiers in the declarations of its move and copy constructors. Moreover, the code can be used with different versions of OpenCV, where the move constructor may not even be available.

class MyClass
{
public:
    MyClass() {}
    MyClass(MyClass&& other)
        : mat{ std::move(other.mat) }
    { }

private:
    MyClass(const MyClass&);

    cv::Mat mat;
};

Generally, if we know or assume that a member of our class may throw an exception, should we still follow this guideline and declare the move constructor noexcept?

I have seen other questions regarding noexcept in move constructors, but they discuss the implementation of the move constructor itself: we shouldn't be allocating memory, calling other code, or anything like that. Ok, I am not doing that. But what if there is just an instance of a class that may throw and we can't change that?

mentalmushroom
  • 2,261
  • 1
  • 26
  • 34
  • Related: [Are move constructors required to be noexcept?](https://stackoverflow.com/questions/9249781/are-move-constructors-required-to-be-noexcept) – Jason Aug 11 '22 at 09:04

1 Answers1

0

If something can throw you must think about the implications. Just marking the function noexcept might result in a call to std::terminate. If you do not care you are free to catch all the exceptions within a noexcept function.

If a move contructor is not marked as noexcept it might disable the usage of move within certain std functions. See Noexcept and copy, move constructors

Since your question is specific to the usage of cv::Mat. This type uses shallow copies by default. I do not like that design choice but one of the very limited benefits is that copying and moving are both rather cheap. The largest difference is the transfer of ownership.

Mehno
  • 868
  • 2
  • 8
  • 21