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?