I am trying to pass a string literal array via an initializer list to a function which only accepts const char**
. Sample code as follows:
// Example program
void foo(const char **) { }
int main() {
using argType = const char*[];
foo(argType{"a","b"});
}
Which doesn't compile in GCC. The error is:
In function 'int main()': 6:25: error: taking address of temporary array
I understand that this argument is a temporary which would be cleaned up after executing this foo(...)
statement. But why is this case considered as an error by the compiler?
Now, if I add std::move
in between:
foo(std::move(argType{"a","b"}));
GCC stops complaining. Why?
The code is correct; argType{"a","b"}
is a prvalue of type const char *[2]
(C++17 [expr.type.conv]/2) , and the array-to-pointer conversion can be applied to an array prvalue ([conv.array]/1) which performs temporary materialization on the prvalue, and the temporary lasts until the end of the full-expression.
So I think this is a gcc bug.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With