Handling “Thrown exception type is not nothrow copy constructible” Warning

丶灬走出姿态 提交于 2019-12-08 15:16:47

问题


Going back to C++ development after a 12 years hiatus. I'm using JetBrains's CLion software which is great since it provides a lot of input on possible issues on my class design. One of the warning I get in my class' constructor throw statement is: Thrown exception type is not nothrow copy constructible. Here is a code sample that generates this warning:

#include <exception>
#include <iostream>

using std::invalid_argument;
using std::string;

class MyClass {
    public:
        explicit MyClass(string value) throw (invalid_argument);
    private:
        string value;
};

MyClass::MyClass(string value) throw (invalid_argument) {
    if (value.length() == 0) {
        throw invalid_argument("YOLO!"); // Warning is here.
    }

    this->value = value;
} 

This piece of code compiles and I am able to unit test it. But I would like very much to get rid of this warning (in order to understand what I am doing wrong, even though it compiles).

Thanks


回答1:


The comment provided by Neil is valid. In C++ 11, using throw in a function signature has been deprecated in favor of noexcept. In this case, my constructor's signature should have been:

explicit MyClass(string value) noexcept(false);

But, since noexcept(false) is applied by default to all functions, unless noexcept or noexcept(true) is specified, I can simply use:

explicit MyClass(string value);

Going back to how to fix the "Thrown exception type is not nothrow copy constructible” warning, I found this post that explains very well what the issue is and how to fix it.



来源:https://stackoverflow.com/questions/46697861/handling-thrown-exception-type-is-not-nothrow-copy-constructible-warning

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!