| Summary: | Unnecessary warning 'Catching by reference is recommended' without parameter name in catch block. | ||
|---|---|---|---|
| Product: | [Tools] CDT | Reporter: | Missing name Mising name <bert> |
| Component: | cdt-codan | Assignee: | CDT Codan Inbox <cdt-codan-inbox> |
| Status: | RESOLVED WONTFIX | QA Contact: | Elena Laskavaia <elaskavaia.cdt> |
| Severity: | normal | ||
| Priority: | P3 | CC: | cdtdoug, Deil.Christoph, malaperle, yevshif, zeratul976 |
| Version: | 8.0 | ||
| Target Milestone: | --- | ||
| Hardware: | PC | ||
| OS: | Windows 7 | ||
| Whiteboard: | |||
I think it might still make sense to catch by reference in this case.
Try the code below and you'll see that an unnecessary copy is made:
g++ -Wall test_exception.cpp && ./a.out
catch(A&) instead and no copy is made.
Before closing this issue, could one of the C++ gurus please comment if there are valid use cases for not catching by reference?
#include <iostream>
#include <string>
struct A {
A(void) {
std::cout << "constructing an A" << std::endl;
s = "content of A";
}
A(const A& other) {
std::cout << "copying an A" << std::endl;
s = other.s;
}
std::string s;
};
int main() {
std::cout << "main" << std::endl;
try {
throw A();
} catch(A) {
std::cout << "catch" << std::endl;
}
std::cout << "end" << std::endl;
return 0;
}
I don't know of any valid use cases for catching by reference. I think the warning is fine as it is. (In reply to comment #2) > I don't know of any valid use cases for catching by reference. I think the > warning is fine as it is. I think you meant for *not* catching by reference? (In reply to comment #3) > (In reply to comment #2) > > I don't know of any valid use cases for catching by reference. I think the > > warning is fine as it is. > > I think you meant for *not* catching by reference? Yes, sorry. I meant "I don't know of any valid use cases for catching by value." |
Build Identifier: 8.0.0.201109151620 Code Analysis gives the warning: Catching by reference is recommended 'std::bad_cast', even when there isn't a parameter name to reference. Example: #include <iostream> #include <exception> class B {}; class A: public B {}; int main() { A obj; try { B& other = dynamic_cast<B&>(obj); } catch (std::bad_cast) { std::cout << "Error casting A to B"; } return 0; } I don't think using std::bad_cast& would give any benefit here. Reproducible: Always Steps to Reproduce: 1. See example code