[docs] Fix build-docs.sh
[llvm-project.git] / clang / www / compatibility.html
bloba593155951dae4f64458ac266e00cea6a1a8b43b
1 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
2 "http://www.w3.org/TR/html4/strict.dtd">
3 <html>
4 <head>
5 <META http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
6 <title>Language Compatibility</title>
7 <link type="text/css" rel="stylesheet" href="menu.css">
8 <link type="text/css" rel="stylesheet" href="content.css">
9 <style type="text/css">
10 </style>
11 </head>
12 <body>
14 <!--#include virtual="menu.html.incl"-->
16 <div id="content">
18 <!-- ======================================================================= -->
19 <h1>Language Compatibility</h1>
20 <!-- ======================================================================= -->
22 <p>Clang strives to both conform to current language standards (up to C11
23 and C++11) and also to implement many widely-used extensions available
24 in other compilers, so that most correct code will "just work" when
25 compiled with Clang. However, Clang is more strict than other
26 popular compilers, and may reject incorrect code that other
27 compilers allow. This page documents common compatibility and
28 portability issues with Clang to help you understand and fix the
29 problem in your code when Clang emits an error message.</p>
31 <ul>
32 <li><a href="#c">C compatibility</a>
33 <ul>
34 <li><a href="#inline">C99 inline functions</a></li>
35 <li><a href="#vector_builtins">"missing" vector __builtin functions</a></li>
36 <li><a href="#lvalue-cast">Lvalue casts</a></li>
37 <li><a href="#blocks-in-protected-scope">Jumps to within <tt>__block</tt> variable scope</a></li>
38 <li><a href="#block-variable-initialization">Non-initialization of <tt>__block</tt> variables</a></li>
39 <li><a href="#inline-asm">Inline assembly</a></li>
40 </ul>
41 </li>
42 <li><a href="#objective-c">Objective-C compatibility</a>
43 <ul>
44 <li><a href="#super-cast">Cast of super</a></li>
45 <li><a href="#sizeof-interface">Size of interfaces</a></li>
46 <li><a href="#objc_objs-cast">Internal Objective-C types</a></li>
47 <li><a href="#c_variables-class">C variables in @class or @protocol</a></li>
48 </ul>
49 </li>
50 <li><a href="#cxx">C++ compatibility</a>
51 <ul>
52 <li><a href="#vla">Variable-length arrays</a></li>
53 <li><a href="#dep_lookup">Unqualified lookup in templates</a></li>
54 <li><a href="#dep_lookup_bases">Unqualified lookup into dependent bases of class templates</a></li>
55 <li><a href="#undep_incomplete">Incomplete types in templates</a></li>
56 <li><a href="#bad_templates">Templates with no valid instantiations</a></li>
57 <li><a href="#default_init_const">Default initialization of const
58 variable of a class type requires user-defined default
59 constructor</a></li>
60 <li><a href="#param_name_lookup">Parameter name lookup</a></li>
61 </ul>
62 </li>
63 <li><a href="#cxx11">C++11 compatibility</a>
64 <ul>
65 <li><a href="#deleted-special-func">Deleted special member
66 functions</a></li>
67 </ul>
68 </li>
69 <li><a href="#objective-cxx">Objective-C++ compatibility</a>
70 <ul>
71 <li><a href="#implicit-downcasts">Implicit downcasts</a></li>
72 </ul>
73 <ul>
74 <li><a href="#class-as-property-name">Using <code>class</code> as a property name</a></li>
75 </ul>
76 </li>
77 </ul>
79 <!-- ======================================================================= -->
80 <h2 id="c">C compatibility</h2>
81 <!-- ======================================================================= -->
83 <!-- ======================================================================= -->
84 <h3 id="inline">C99 inline functions</h3>
85 <!-- ======================================================================= -->
86 <p>By default, Clang builds C code in GNU C17 mode, so it uses standard C99
87 semantics for the <code>inline</code> keyword. These semantics are different
88 from those in GNU C89 mode, which is the default mode in versions of GCC
89 prior to 5.0. For example, consider the following code:</p>
90 <pre>
91 inline int add(int i, int j) { return i + j; }
93 int main() {
94 int i = add(4, 5);
95 return i;
97 </pre>
99 <p>In C99, <code>inline</code> means that a function's definition is
100 provided only for inlining, and that there is another definition
101 (without <code>inline</code>) somewhere else in the program. That
102 means that this program is incomplete, because if <code>add</code>
103 isn't inlined (for example, when compiling without optimization), then
104 <code>main</code> will have an unresolved reference to that other
105 definition. Therefore we'll get a (correct) link-time error like this:</p>
107 <pre>
108 Undefined symbols:
109 "_add", referenced from:
110 _main in cc-y1jXIr.o
111 </pre>
113 <p>By contrast, GNU C89 mode (used by default in older versions of GCC) is the
114 C89 standard plus a lot of extensions. C89 doesn't have an <code>inline</code>
115 keyword, but GCC recognizes it as an extension and just treats it as a hint to
116 the optimizer.</p>
118 <p>There are several ways to fix this problem:</p>
120 <ul>
121 <li>Change <code>add</code> to a <code>static inline</code>
122 function. This is usually the right solution if only one
123 translation unit needs to use the function. <code>static
124 inline</code> functions are always resolved within the translation
125 unit, so you won't have to add a non-<code>inline</code> definition
126 of the function elsewhere in your program.</li>
128 <li>Remove the <code>inline</code> keyword from this definition of
129 <code>add</code>. The <code>inline</code> keyword is not required
130 for a function to be inlined, nor does it guarantee that it will be.
131 Some compilers ignore it completely. Clang treats it as a mild
132 suggestion from the programmer.</li>
134 <li>Provide an external (non-<code>inline</code>) definition
135 of <code>add</code> somewhere else in your program. The two
136 definitions must be equivalent!</li>
138 <li>Compile in the GNU C89 dialect by adding
139 <code>-std=gnu89</code> to the set of Clang options. This option is
140 only recommended if the program source cannot be changed or if the
141 program also relies on additional C89-specific behavior that cannot
142 be changed.</li>
143 </ul>
145 <p>All of this only applies to C code; the meaning of <code>inline</code>
146 in C++ is very different from its meaning in either GNU89 or C99.</p>
148 <!-- ======================================================================= -->
149 <h3 id="vector_builtins">"missing" vector __builtin functions</h3>
150 <!-- ======================================================================= -->
152 <p>The Intel and AMD manuals document a number "<tt>&lt;*mmintrin.h&gt;</tt>"
153 header files, which define a standardized API for accessing vector operations
154 on X86 CPUs. These functions have names like <tt>_mm_xor_ps</tt> and
155 <tt>_mm256_addsub_pd</tt>. Compilers have leeway to implement these functions
156 however they want. Since Clang supports an excellent set of <a
157 href="../docs/LanguageExtensions.html#vectors">native vector operations</a>,
158 the Clang headers implement these interfaces in terms of the native vector
159 operations.
160 </p>
162 <p>In contrast, GCC implements these functions mostly as a 1-to-1 mapping to
163 builtin function calls, like <tt>__builtin_ia32_paddw128</tt>. These builtin
164 functions are an internal implementation detail of GCC, and are not portable to
165 the Intel compiler, the Microsoft compiler, or Clang. If you get build errors
166 mentioning these, the fix is simple: switch to the *mmintrin.h functions.</p>
168 <p>The same issue occurs for NEON and Altivec for the ARM and PowerPC
169 architectures respectively. For these, make sure to use the &lt;arm_neon.h&gt;
170 and &lt;altivec.h&gt; headers.</p>
172 <p>For x86 architectures this <a href="builtins.py">script</a> should help with
173 the manual migration process. It will rewrite your source files in place to
174 use the APIs instead of builtin function calls. Just call it like this:</p>
176 <pre>
177 builtins.py *.c *.h
178 </pre>
180 <p>and it will rewrite all of the .c and .h files in the current directory to
181 use the API calls instead of calls like <tt>__builtin_ia32_paddw128</tt>.</p>
183 <!-- ======================================================================= -->
184 <h3 id="lvalue-cast">Lvalue casts</h3>
185 <!-- ======================================================================= -->
187 <p>Old versions of GCC permit casting the left-hand side of an assignment to a
188 different type. Clang produces an error on similar code, e.g.,</p>
190 <pre>
191 <b>lvalue.c:2:3: <span class="error">error:</span> assignment to cast is illegal, lvalue casts are not supported</b>
192 (int*)addr = val;
193 <span class="caret"> ^~~~~~~~~~ ~</span>
194 </pre>
196 <p>To fix this problem, move the cast to the right-hand side. In this
197 example, one could use:</p>
199 <pre>
200 addr = (float *)val;
201 </pre>
203 <!-- ======================================================================= -->
204 <h3 id="blocks-in-protected-scope">Jumps to within <tt>__block</tt> variable scope</h3>
205 <!-- ======================================================================= -->
207 <p>Clang disallows jumps into the scope of a <tt>__block</tt>
208 variable. Variables marked with <tt>__block</tt> require special
209 runtime initialization. A jump into the scope of a <tt>__block</tt>
210 variable bypasses this initialization, leaving the variable's metadata
211 in an invalid state. Consider the following code fragment:</p>
213 <pre>
214 int fetch_object_state(struct MyObject *c) {
215 if (!c->active) goto error;
217 __block int result;
218 run_specially_somehow(^{ result = c->state; });
219 return result;
221 error:
222 fprintf(stderr, "error while fetching object state");
223 return -1;
225 </pre>
227 <p>GCC accepts this code, but it produces code that will usually crash
228 when <code>result</code> goes out of scope if the jump is taken. (It's
229 possible for this bug to go undetected because it often won't crash if
230 the stack is fresh, i.e. still zeroed.) Therefore, Clang rejects this
231 code with a hard error:</p>
233 <pre>
234 <b>t.c:3:5: <span class="error">error:</span> goto into protected scope</b>
235 goto error;
236 <span class="caret"> ^</span>
237 <b>t.c:5:15: <span class="note">note:</note></b> jump bypasses setup of __block variable
238 __block int result;
239 <span class="caret"> ^</span>
240 </pre>
242 <p>The fix is to rewrite the code to not require jumping into a
243 <tt>__block</tt> variable's scope, e.g. by limiting that scope:</p>
245 <pre>
247 __block int result;
248 run_specially_somehow(^{ result = c->state; });
249 return result;
251 </pre>
253 <!-- ======================================================================= -->
254 <h3 id="block-variable-initialization">Non-initialization of <tt>__block</tt>
255 variables</h3>
256 <!-- ======================================================================= -->
258 <p>In the following example code, the <tt>x</tt> variable is used before it is
259 defined:</p>
260 <pre>
261 int f0() {
262 __block int x;
263 return ^(){ return x; }();
265 </pre>
267 <p>By an accident of implementation, GCC and llvm-gcc unintentionally always
268 zero initialized <tt>__block</tt> variables. However, any program which depends
269 on this behavior is relying on unspecified compiler behavior. Programs must
270 explicitly initialize all local block variables before they are used, as with
271 other local variables.</p>
273 <p>Clang does not zero initialize local block variables, and programs which rely
274 on such behavior will most likely break when built with Clang.</p>
277 <!-- ======================================================================= -->
278 <h3 id="inline-asm">Inline assembly</h3>
279 <!-- ======================================================================= -->
281 <p>In general, Clang is highly compatible with the GCC inline assembly
282 extensions, allowing the same set of constraints, modifiers and operands as GCC
283 inline assembly.</p>
285 <p>On targets that use the integrated assembler (such as most X86 targets),
286 inline assembly is run through the integrated assembler instead of your system
287 assembler (which is most commonly "gas", the GNU assembler). The LLVM
288 integrated assembler is extremely compatible with GAS, but there are a couple of
289 minor places where it is more picky, particularly due to outright GAS bugs.</p>
291 <p>One specific example is that the assembler rejects ambiguous X86 instructions
292 that don't have suffixes. For example:</p>
294 <pre>
295 asm("add %al, (%rax)");
296 asm("addw $4, (%rax)");
297 asm("add $4, (%rax)");
298 </pre>
300 <p>Both clang and GAS accept the first instruction: because the first
301 instruction uses the 8-bit <tt>%al</tt> register as an operand, it is clear that
302 it is an 8-bit add. The second instruction is accepted by both because the "w"
303 suffix indicates that it is a 16-bit add. The last instruction is accepted by
304 GAS even though there is nothing that specifies the size of the instruction (and
305 the assembler randomly picks a 32-bit add). Because it is ambiguous, Clang
306 rejects the instruction with this error message:
307 </p>
309 <pre>
310 <b>&lt;inline asm&gt;:3:1: <span class="error">error:</span> ambiguous instructions require an explicit suffix (could be 'addb', 'addw', 'addl', or 'addq')</b>
311 add $4, (%rax)
312 <span class="caret">^</span>
313 </pre>
315 <p>To fix this compatibility issue, add an explicit suffix to the instruction:
316 this makes your code more clear and is compatible with both GCC and Clang.</p>
318 <!-- ======================================================================= -->
319 <h2 id="objective-c">Objective-C compatibility</h2>
320 <!-- ======================================================================= -->
322 <!-- ======================================================================= -->
323 <h3 id="super-cast">Cast of super</h3>
324 <!-- ======================================================================= -->
326 <p>GCC treats the <code>super</code> identifier as an expression that
327 can, among other things, be cast to a different type. Clang treats
328 <code>super</code> as a context-sensitive keyword, and will reject a
329 type-cast of <code>super</code>:</p>
331 <pre>
332 <b>super.m:11:12: <span class="error">error:</span> cannot cast 'super' (it isn't an expression)</b>
333 [(Super*)super add:4];
334 <span class="caret"> ~~~~~~~~^</span>
335 </pre>
337 <p>To fix this problem, remove the type cast, e.g.</p>
338 <pre>
339 [super add:4];
340 </pre>
342 <!-- ======================================================================= -->
343 <h3 id="sizeof-interface">Size of interfaces</h3>
344 <!-- ======================================================================= -->
346 <p>When using the "non-fragile" Objective-C ABI in use, the size of an
347 Objective-C class may change over time as instance variables are added
348 (or removed). For this reason, Clang rejects the application of the
349 <code>sizeof</code> operator to an Objective-C class when using this
350 ABI:</p>
352 <pre>
353 <b>sizeof.m:4:14: <span class="error">error:</span> invalid application of 'sizeof' to interface 'NSArray' in non-fragile ABI</b>
354 int size = sizeof(NSArray);
355 <span class="caret"> ^ ~~~~~~~~~</span>
356 </pre>
358 <p>Code that relies on the size of an Objective-C class is likely to
359 be broken anyway, since that size is not actually constant. To address
360 this problem, use the Objective-C runtime API function
361 <code>class_getInstanceSize()</code>:</p>
363 <pre>
364 class_getInstanceSize([NSArray class])
365 </pre>
367 <!-- ======================================================================= -->
368 <h3 id="objc_objs-cast">Internal Objective-C types</h3>
369 <!-- ======================================================================= -->
371 <p>GCC allows using pointers to internal Objective-C objects, <tt>struct objc_object*</tt>,
372 <tt>struct objc_selector*</tt>, and <tt>struct objc_class*</tt> in place of the types
373 <tt>id</tt>, <tt>SEL</tt>, and <tt>Class</tt> respectively. Clang treats the
374 internal Objective-C structures as implementation detail and won't do implicit conversions:
376 <pre>
377 <b>t.mm:11:2: <span class="error">error:</span> no matching function for call to 'f'</b>
378 f((struct objc_object *)p);
379 <span class="caret"> ^</span>
380 <b>t.mm:5:6: <span class="note">note:</note></b> candidate function not viable: no known conversion from 'struct objc_object *' to 'id' for 1st argument
381 void f(id x);
382 <span class="caret"> ^</span>
383 </pre>
385 <p>Code should use types <tt>id</tt>, <tt>SEL</tt>, and <tt>Class</tt>
386 instead of the internal types.</p>
388 <!-- ======================================================================= -->
389 <h3 id="c_variables-class">C variables in @interface or @protocol</h3>
390 <!-- ======================================================================= -->
392 <p>GCC allows the declaration of C variables in
393 an <code>@interface</code> or <code>@protocol</code>
394 declaration. Clang does not allow variable declarations to appear
395 within these declarations unless they are marked <code>extern</code>.</p>
397 <p>Variables may still be declared in an @implementation.</p>
399 <pre>
400 @interface XX
401 int a; // not allowed in clang
402 int b = 1; // not allowed in clang
403 extern int c; // allowed
404 @end
406 </pre>
408 <!-- ======================================================================= -->
409 <h2 id="cxx">C++ compatibility</h2>
410 <!-- ======================================================================= -->
412 <!-- ======================================================================= -->
413 <h3 id="vla">Variable-length arrays</h3>
414 <!-- ======================================================================= -->
416 <p>GCC and C99 allow an array's size to be determined at run
417 time. This extension is not permitted in standard C++. However, Clang
418 supports such variable length arrays for compatibility with GNU C and
419 C99 programs.</p>
421 <p>If you would prefer not to use this extension, you can disable it with
422 <tt>-Werror=vla</tt>. There are several ways to fix your code:
424 <ol>
425 <li>replace the variable length array with a fixed-size array if you can
426 determine a reasonable upper bound at compile time; sometimes this is as
427 simple as changing <tt>int size = ...;</tt> to <tt>const int size
428 = ...;</tt> (if the initializer is a compile-time constant);</li>
429 <li>use <tt>std::vector</tt> or some other suitable container type;
430 or</li>
431 <li>allocate the array on the heap instead using <tt>new Type[]</tt> -
432 just remember to <tt>delete[]</tt> it.</li>
433 </ol>
435 <!-- ======================================================================= -->
436 <h3 id="dep_lookup">Unqualified lookup in templates</h3>
437 <!-- ======================================================================= -->
439 <p>Some versions of GCC accept the following invalid code:
441 <pre>
442 template &lt;typename T&gt; T Squared(T x) {
443 return Multiply(x, x);
446 int Multiply(int x, int y) {
447 return x * y;
450 int main() {
451 Squared(5);
453 </pre>
455 <p>Clang complains:
457 <pre>
458 <b>my_file.cpp:2:10: <span class="error">error:</span> call to function 'Multiply' that is neither visible in the template definition nor found by argument-dependent lookup</b>
459 return Multiply(x, x);
460 <span class="caret"> ^</span>
461 <b>my_file.cpp:10:3: <span class="note">note:</span></b> in instantiation of function template specialization 'Squared&lt;int&gt;' requested here
462 Squared(5);
463 <span class="caret"> ^</span>
464 <b>my_file.cpp:5:5: <span class="note">note:</span></b> 'Multiply' should be declared prior to the call site
465 int Multiply(int x, int y) {
466 <span class="caret"> ^</span>
467 </pre>
469 <p>The C++ standard says that unqualified names like <q>Multiply</q>
470 are looked up in two ways.
472 <p>First, the compiler does <i>unqualified lookup</i> in the scope
473 where the name was written. For a template, this means the lookup is
474 done at the point where the template is defined, not where it's
475 instantiated. Since <tt>Multiply</tt> hasn't been declared yet at
476 this point, unqualified lookup won't find it.
478 <p>Second, if the name is called like a function, then the compiler
479 also does <i>argument-dependent lookup</i> (ADL). (Sometimes
480 unqualified lookup can suppress ADL; see [basic.lookup.argdep]p3 for
481 more information.) In ADL, the compiler looks at the types of all the
482 arguments to the call. When it finds a class type, it looks up the
483 name in that class's namespace; the result is all the declarations it
484 finds in those namespaces, plus the declarations from unqualified
485 lookup. However, the compiler doesn't do ADL until it knows all the
486 argument types.
488 <p>In our example, <tt>Multiply</tt> is called with dependent
489 arguments, so ADL isn't done until the template is instantiated. At
490 that point, the arguments both have type <tt>int</tt>, which doesn't
491 contain any class types, and so ADL doesn't look in any namespaces.
492 Since neither form of lookup found the declaration
493 of <tt>Multiply</tt>, the code doesn't compile.
495 <p>Here's another example, this time using overloaded operators,
496 which obey very similar rules.
498 <pre>#include &lt;iostream&gt;
500 template&lt;typename T&gt;
501 void Dump(const T&amp; value) {
502 std::cout &lt;&lt; value &lt;&lt; "\n";
505 namespace ns {
506 struct Data {};
509 std::ostream&amp; operator&lt;&lt;(std::ostream&amp; out, ns::Data data) {
510 return out &lt;&lt; "Some data";
513 void Use() {
514 Dump(ns::Data());
515 }</pre>
517 <p>Again, Clang complains:</p>
519 <pre>
520 <b>my_file2.cpp:5:13: <span class="error">error:</span> call to function 'operator&lt;&lt;' that is neither visible in the template definition nor found by argument-dependent lookup</b>
521 std::cout &lt;&lt; value &lt;&lt; "\n";
522 <span class="caret"> ^</span>
523 <b>my_file2.cpp:17:3: <span class="note">note:</span></b> in instantiation of function template specialization 'Dump&lt;ns::Data&gt;' requested here
524 Dump(ns::Data());
525 <span class="caret"> ^</span>
526 <b>my_file2.cpp:12:15: <span class="note">note:</span></b> 'operator&lt;&lt;' should be declared prior to the call site or in namespace 'ns'
527 std::ostream&amp; operator&lt;&lt;(std::ostream&amp; out, ns::Data data) {
528 <span class="caret"> ^</span>
529 </pre>
531 <p>Just like before, unqualified lookup didn't find any declarations
532 with the name <tt>operator&lt;&lt;</tt>. Unlike before, the argument
533 types both contain class types: one of them is an instance of the
534 class template type <tt>std::basic_ostream</tt>, and the other is the
535 type <tt>ns::Data</tt> that we declared above. Therefore, ADL will
536 look in the namespaces <tt>std</tt> and <tt>ns</tt> for
537 an <tt>operator&lt;&lt;</tt>. Since one of the argument types was
538 still dependent during the template definition, ADL isn't done until
539 the template is instantiated during <tt>Use</tt>, which means that
540 the <tt>operator&lt;&lt;</tt> we want it to find has already been
541 declared. Unfortunately, it was declared in the global namespace, not
542 in either of the namespaces that ADL will look in!
544 <p>There are two ways to fix this problem:</p>
545 <ol><li>Make sure the function you want to call is declared before the
546 template that might call it. This is the only option if none of its
547 argument types contain classes. You can do this either by moving the
548 template definition, or by moving the function definition, or by
549 adding a forward declaration of the function before the template.</li>
550 <li>Move the function into the same namespace as one of its arguments
551 so that ADL applies.</li></ol>
553 <p>For more information about argument-dependent lookup, see
554 [basic.lookup.argdep]. For more information about the ordering of
555 lookup in templates, see [temp.dep.candidate].
557 <!-- ======================================================================= -->
558 <h3 id="dep_lookup_bases">Unqualified lookup into dependent bases of class templates</h3>
559 <!-- ======================================================================= -->
561 <p>Some versions of GCC accept the following invalid code:
563 <pre>
564 template &lt;typename T&gt; struct Base {
565 void DoThis(T x) {}
566 static void DoThat(T x) {}
569 template &lt;typename T&gt; struct Derived : public Base&lt;T&gt; {
570 void Work(T x) {
571 DoThis(x); // Invalid!
572 DoThat(x); // Invalid!
575 </pre>
577 Clang correctly rejects it with the following errors
578 (when <tt>Derived</tt> is eventually instantiated):
580 <pre>
581 <b>my_file.cpp:8:5: <span class="error">error:</span> use of undeclared identifier 'DoThis'</b>
582 DoThis(x);
583 <span class="caret"> ^</span>
584 this-&gt;
585 <b>my_file.cpp:2:8: <span class="note">note:</note></b> must qualify identifier to find this declaration in dependent base class
586 void DoThis(T x) {}
587 <span class="caret"> ^</span>
588 <b>my_file.cpp:9:5: <span class="error">error:</span> use of undeclared identifier 'DoThat'</b>
589 DoThat(x);
590 <span class="caret"> ^</span>
591 this-&gt;
592 <b>my_file.cpp:3:15: <span class="note">note:</note></b> must qualify identifier to find this declaration in dependent base class
593 static void DoThat(T x) {}
594 </pre>
596 Like we said <a href="#dep_lookup">above</a>, unqualified names like
597 <tt>DoThis</tt> and <tt>DoThat</tt> are looked up when the template
598 <tt>Derived</tt> is defined, not when it's instantiated. When we look
599 up a name used in a class, we usually look into the base classes.
600 However, we can't look into the base class <tt>Base&lt;T&gt;</tt>
601 because its type depends on the template argument <tt>T</tt>, so the
602 standard says we should just ignore it. See [temp.dep]p3 for details.
604 <p>The fix, as Clang tells you, is to tell the compiler that we want a
605 class member by prefixing the calls with <tt>this-&gt;</tt>:
607 <pre>
608 void Work(T x) {
609 <b>this-&gt;</b>DoThis(x);
610 <b>this-&gt;</b>DoThat(x);
612 </pre>
614 Alternatively, you can tell the compiler exactly where to look:
616 <pre>
617 void Work(T x) {
618 <b>Base&lt;T&gt;</b>::DoThis(x);
619 <b>Base&lt;T&gt;</b>::DoThat(x);
621 </pre>
623 This works whether the methods are static or not, but be careful:
624 if <tt>DoThis</tt> is virtual, calling it this way will bypass virtual
625 dispatch!
627 <!-- ======================================================================= -->
628 <h3 id="undep_incomplete">Incomplete types in templates</h3>
629 <!-- ======================================================================= -->
631 <p>The following code is invalid, but compilers are allowed to accept it:
633 <pre>
634 class IOOptions;
635 template &lt;class T&gt; bool read(T &amp;value) {
636 IOOptions opts;
637 return read(opts, value);
640 class IOOptions { bool ForceReads; };
641 bool read(const IOOptions &amp;opts, int &amp;x);
642 template bool read&lt;&gt;(int &amp;);
643 </pre>
645 The standard says that types which don't depend on template parameters
646 must be complete when a template is defined if they affect the
647 program's behavior. However, the standard also says that compilers
648 are free to not enforce this rule. Most compilers enforce it to some
649 extent; for example, it would be an error in GCC to
650 write <tt>opts.ForceReads</tt> in the code above. In Clang, we feel
651 that enforcing the rule consistently lets us provide a better
652 experience, but unfortunately it also means we reject some code that
653 other compilers accept.
655 <p>We've explained the rule here in very imprecise terms; see
656 [temp.res]p8 for details.
658 <!-- ======================================================================= -->
659 <h3 id="bad_templates">Templates with no valid instantiations</h3>
660 <!-- ======================================================================= -->
662 <p>The following code contains a typo: the programmer
663 meant <tt>init()</tt> but wrote <tt>innit()</tt> instead.
665 <pre>
666 template &lt;class T&gt; class Processor {
668 void init();
672 template &lt;class T&gt; void process() {
673 Processor&lt;T&gt; processor;
674 processor.innit(); // <-- should be 'init()'
677 </pre>
679 Unfortunately, we can't flag this mistake as soon as we see it: inside
680 a template, we're not allowed to make assumptions about "dependent
681 types" like <tt>Processor&lt;T&gt;</tt>. Suppose that later on in
682 this file the programmer adds an explicit specialization
683 of <tt>Processor</tt>, like so:
685 <pre>
686 template &lt;&gt; class Processor&lt;char*&gt; {
687 void innit();
689 </pre>
691 Now the program will work &mdash; as long as the programmer only ever
692 instantiates <tt>process()</tt> with <tt>T = char*</tt>! This is why
693 it's hard, and sometimes impossible, to diagnose mistakes in a
694 template definition before it's instantiated.
696 <p>The standard says that a template with no valid instantiations is
697 ill-formed. Clang tries to do as much checking as possible at
698 definition-time instead of instantiation-time: not only does this
699 produce clearer diagnostics, but it also substantially improves
700 compile times when using pre-compiled headers. The downside to this
701 philosophy is that Clang sometimes fails to process files because they
702 contain broken templates that are no longer used. The solution is
703 simple: since the code is unused, just remove it.
705 <!-- ======================================================================= -->
706 <h3 id="default_init_const">Default initialization of const variable of a class type requires user-defined default constructor</h3>
707 <!-- ======================================================================= -->
709 <p>If a <tt>class</tt> or <tt>struct</tt> has no user-defined default
710 constructor, C++ doesn't allow you to default construct a <tt>const</tt>
711 instance of it like this ([dcl.init], p9):
713 <pre>
714 class Foo {
715 public:
716 // The compiler-supplied default constructor works fine, so we
717 // don't bother with defining one.
721 void Bar() {
722 const Foo foo; // Error!
725 </pre>
727 To fix this, you can define a default constructor for the class:
729 <pre>
730 class Foo {
731 public:
732 Foo() {}
736 void Bar() {
737 const Foo foo; // Now the compiler is happy.
740 </pre>
742 An upcoming change to the C++ standard is expected to weaken this rule to only
743 apply when the compiler-supplied default constructor would leave a member
744 uninitialized. Clang implements the more relaxed rule in version 3.8 onwards.
746 <!-- ======================================================================= -->
747 <h3 id="param_name_lookup">Parameter name lookup</h3>
748 <!-- ======================================================================= -->
750 <p>Some versions of GCC allow the redeclaration of function parameter names within a function prototype in C++ code, e.g.</p>
751 <blockquote>
752 <pre>
753 void f(int a, int a);
754 </pre>
755 </blockquote>
756 <p>Clang diagnoses this error (where the parameter name has been redeclared). To fix this problem, rename one of the parameters.</p>
758 <!-- ======================================================================= -->
759 <h2 id="cxx11">C++11 compatibility</h2>
760 <!-- ======================================================================= -->
762 <!-- ======================================================================= -->
763 <h3 id="deleted-special-func">Deleted special member functions</h3>
764 <!-- ======================================================================= -->
766 <p>In C++11, the explicit declaration of a move constructor or a move
767 assignment operator within a class deletes the implicit declaration
768 of the copy constructor and copy assignment operator. This change came
769 fairly late in the C++11 standardization process, so early
770 implementations of C++11 (including Clang before 3.0, GCC before 4.7,
771 and Visual Studio 2010) do not implement this rule, leading them to
772 accept this ill-formed code:</p>
774 <pre>
775 struct X {
776 X(X&amp;&amp;); <i>// deletes implicit copy constructor:</i>
777 <i>// X(const X&amp;) = delete;</i>
780 void f(X x);
781 void g(X x) {
782 f(x); <i>// error: X has a deleted copy constructor</i>
784 </pre>
786 <p>This affects some early C++11 code, including Boost's popular <a
787 href="https://www.boost.org/doc/libs/release/libs/smart_ptr/shared_ptr.htm"><tt>shared_ptr</tt></a>
788 up to version 1.47.0. The fix for Boost's <tt>shared_ptr</tt> is
789 <a href="https://svn.boost.org/trac/boost/changeset/73202">available here</a>.</p>
791 <!-- ======================================================================= -->
792 <h2 id="objective-cxx">Objective-C++ compatibility</h2>
793 <!-- ======================================================================= -->
795 <!-- ======================================================================= -->
796 <h3 id="implicit-downcasts">Implicit downcasts</h3>
797 <!-- ======================================================================= -->
799 <p>Due to a bug in its implementation, GCC allows implicit downcasts
800 of Objective-C pointers (from a base class to a derived class) when
801 calling functions. Such code is inherently unsafe, since the object
802 might not actually be an instance of the derived class, and is
803 rejected by Clang. For example, given this code:</p>
805 <pre>
806 @interface Base @end
807 @interface Derived : Base @end
809 void f(Derived *p);
810 void g(Base *p) {
811 f(p);
813 </pre>
815 <p>Clang produces the following error:</p>
817 <pre>
818 <b>downcast.mm:6:3: <span class="error">error:</span> no matching function for call to 'f'</b>
819 f(p);
820 <span class="caret"> ^</span>
821 <b>downcast.mm:4:6: <span class="note">note:</note></b> candidate function not viable: cannot convert from
822 superclass 'Base *' to subclass 'Derived *' for 1st argument
823 void f(Derived *p);
824 <span class="caret"> ^</span>
825 </pre>
827 <p>If the downcast is actually correct (e.g., because the code has
828 already checked that the object has the appropriate type), add an
829 explicit cast:</p>
831 <pre>
832 f((Derived *)base);
833 </pre>
835 <!-- ======================================================================= -->
836 <h3 id="class-as-property-name">Using <code>class</code> as a property name</h3>
837 <!-- ======================================================================= -->
839 <p>In C and Objective-C, <code>class</code> is a normal identifier and
840 can be used to name fields, ivars, methods, and so on. In
841 C++, <code>class</code> is a keyword. For compatibility with existing
842 code, Clang permits <code>class</code> to be used as part of a method
843 selector in Objective-C++, but this does not extend to any other part
844 of the language. In particular, it is impossible to use property dot
845 syntax in Objective-C++ with the property name <code>class</code>, so
846 the following code will fail to parse:</p>
848 <pre>
849 @interface I {
850 int cls;
852 + (int)class;
853 @end
855 @implementation I
856 - (int) Meth { return I.class; }
857 @end
858 </pre>
860 <p>Use explicit message-send syntax instead, i.e. <code>[I class]</code>.</p>
862 </div>
863 </body>
864 </html>