这是什么?按值捕获多态类型 X [-Wcatch-value=]

not*_*orb 5 c++

有谁知道以下编译warning: catching polymorphic type ‘class std::out_of_range’ by value [-Wcatch-value=]警告的含义以及如何纠正它?我从 Stroustrup 的 C++ 4th Edition 字面上复制了这个代码块。谢谢

#include <iostream>
#include <vector>
#include <list>
using std::vector;
using std::list;
using std::cout;

template <typename T>
class Vec : public vector<T> {
 public:
  using vector<T>::vector;  // constructor

  T& operator[](int i) { return vector<T>::at(i); }
  const T& operator[](int i) const { return vector<T>::at(i); }
};

int main(int argc, char* argv[]) {
  vector<int> v0 = {0, 1, 2};
  Vec<int> v1 = {0, 1, 2};

  cout << v0[v0.size()] << '\n';  // no error

  try {
    cout << v1[v1.size()];  // out of range
  } catch (std::out_of_range) {
    cout << "tried out of range" << '\n';
  }

  return 0;
}
Run Code Online (Sandbox Code Playgroud)

错误:

$ g++ -Wall -pedantic -std=c++11 test69.cc && ./a.out
test69.cc: In function ‘int main(int, char**)’:
test69.cc:32:17: warning: catching polymorphic type ‘class std::out_of_range’ by value [-Wcatch-value=]
   } catch (std::out_of_range) {
                 ^~~~~~~~~~~~
0
tried out of range
Run Code Online (Sandbox Code Playgroud)

Cor*_*mer 12

您应该将其修改为

catch (std::out_of_range const&)
Run Code Online (Sandbox Code Playgroud)

该消息警告您多态仅适用于引用和指针

  • 我建议详细说明答案。 (3认同)

Ami*_*ory 9

如果您查看 C++ 核心指南,您可以找到

E.15:通过引用从层次结构中捕获异常

这正是你的情况。通过捕获一个值,您可以有效地仅使用所抛出异常的基类(无论实际抛出的类型如何)。相反,通过引用捕获(或常量引用,如果您不打算修改异常),以保留多态行为。