Hello,<br><br>I was involved in a discussion recently where a beginner fell into the trap of object slicing.<br><br>After a quick scan through the Standard and a search on Google I haven't found anything indicating whether slicing is well-defined or not, though in any case it is always surprising.<br>
<br>I put together a small test file (in attachment) which exposes variations of:<br><br><div style="margin-left: 40px;">struct B {};<br><br>struct V { virtual ~V() {} };<br><br>// Constructor<br>void noslice0(B const& x, B& y, B&& z) {<br>
  B a(x); (void)a;<br>  B b(y); (void)b;<br>  B c(z); (void)c;<br>}<br><br>void slice0(V const& x, V& y, V&& z) {<br>  V a(x); (void)a;<br>  V b(y); (void)b;<br>  V c(z); (void)c;<br>}<br></div><br>Using the following command line:<br>
<br><div style="margin-left: 40px;">$ clang -fsyntax-only -std=c++0x -Weverything -Wno-missing-prototypes -Wno-weak-vtables slicing.cpp<br></div><br>Clang does not emit any warning for the potential slicing cases (thanks Ted for the discovery mode made easy).<br>
<br>(Note: the test case here intentionally leave out the case where the class has virtual methods but is itself final, or when all methods are final)<br><br><br>I was wondering if there was interest in such a warning ?<br>
<br>There are potentially two approaches, as far as I see it:<br><br>> Warn on the class declaration whenever it's usable as a base class (polymorphic + non-final) if the copy/move operators are public<br><div style="margin-left: 40px;">
It's the easiest approach, but is likely to be noisy on unexposed code bases. I don't like this warning mode for non-virtual destructors already...<br></div><br>> Warn whenever a (potentially) slicing conversion occur.<br>
<div style="margin-left: 40px;">It may be interesting to distinguish between a known occurrence and a potential occurrence (using 2 variants of the analysis/warning)<br>It may be significantly harder to introduce as a number of expressions may have this issue.<br>
</div><br><br>Remarks and opinions welcome :)<br><br>-- Matthieu<br>