LoginSignup
2
2

More than 5 years have passed since last update.

警告特盛りにしてたらBoost.Pythonのサンプルコードが通らなかった話

Posted at

C++サイドで何か例外的な状態になったら、さくっと例外を投げて通知したい。とはいえプロトタイプづくりの段階でいちいち個別の例外クラスを作ったりするのは面倒。

そこでHeader <boost/python/exception_translator.hpp>のサンプルコードを流用して、コンストラクタが文字列を取るようにしようとおもった。

struct my_exception : std::exception
{
    char const* what() throw() { return "One of my exceptions"; }
};

void translate(my_exception const& e)
{
    PyErr_SetString(PyExc_RuntimeError, e.what());
}

void something_which_throws()
{
    ...
    throw my_exception();
    ...
}

しかし、このサンプルは下記のコンパイルエラーになってしまう。

hello.cpp:39:46: error: passing ‘const my_exception’ as ‘this’ argument of ‘const char* my_exception::what()’ discards qualifiers [-fpermissive] 

原因はwhat()がconst methodでないせい。「translateがeをconst参照で受けてるのにwhatメソッド呼んでるけど、これオブジェクトを破壊的に書き換えたりしないの?」と言われている。「whatメソッドはオブジェクトの状態を書き換えたりしないよー」と宣言してやる必要がある。

char const* what() const throw() { return "One of my exceptions"; } 

めでたしめでたし。

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2