Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does passing a temporary object as an argument need std::move?

Tags:

c++

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?

like image 644
dchneric Avatar asked Apr 01 '19 21:04

dchneric


1 Answers

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.

like image 72
M.M Avatar answered Sep 28 '22 19:09

M.M