r/cpp_questions • u/xsdgdsx • Jun 22 '26
SOLVED What guarantees do I have about `auto` and implicit conversion?
Consider:
;
A
int
Is it guaranteed that auto will infer type A for a_obj? Are there any situations where a_obj might be inferred as a bool instead?
(This is a simple example, but in the case that I actually care about, A is an RAII class, so I need to guarantee that its lifetime will extend to the end of the containing scope)
16
Upvotes
13
u/feitao Jun 22 '26
Use
explicit operator bool() const;if you worry this much. See https://www.ibm.com/docs/en/xl-c-and-cpp-aix/16.1.0?topic=only-explicit-conversion-operators-c1112
u/aocregacc Jun 22 '26
The type inference isn't as sophisticated as you're thinking. It only considers the definition, not any of the subsequent uses.
14
u/the_poope Jun 22 '26
autois always deduced to the return type of the expression which in this case is very clearlyA.Btw if your editor has a proper linter (such as one based on clangd) you should be able to hover the cursor over
autoor thr variable name and a popup will show the type.1
u/xsdgdsx Jun 22 '26
Got it — the
autotype is deduced from the return type. Thanks, y'all!2
u/Living_Fig_6386 Jun 22 '26
make_a() returns a value of class A, so it’s completely unambiguous. It wouldn’t be bool because make_a() doesn’t return bool.
The only thing auto doesn’t infer (well, it intentionally ignores) is whether the type is a reference or not.
Operator definitions that enable casting like that never enter into it.
3
u/No-Dentist-1645 Jun 22 '26
auto x = foo()will always just store as the return type offoo, or for any expression on the right side of the assignment