<table border="1" cellspacing="0" cellpadding="8">
<tr>
<th>Issue</th>
<td>
<a href=https://github.com/llvm/llvm-project/issues/149661>149661</a>
</td>
</tr>
<tr>
<th>Summary</th>
<td>
Possibly missed allocation elision
</td>
</tr>
<tr>
<th>Labels</th>
<td>
new issue
</td>
</tr>
<tr>
<th>Assignees</th>
<td>
</td>
</tr>
<tr>
<th>Reporter</th>
<td>
rohanlean
</td>
</tr>
</table>
<pre>
(Crossposted to [GCC bugzilla](https://gcc.gnu.org/bugzilla/show_bug.cgi?id=121177))
I am unsure if the optimisations I desire are allowed by the standard, so in that sense this report is half a question. I believe it comes down mostly to the interpretation of [expr.new](§§ 14 ff.) and possibly somewhat to that of [basic.stc.dynamic.allocation](§ 2).
I am mildly convinced that the following code can omit all but one allocation and all copying.
```
#include <vector>
#include <memory>
#include <span>
void g(char *p, unsigned int n) noexcept;
static auto h(unsigned int n) noexcept -> std::unique_ptr<char[]>
{
auto x = std::make_unique_for_overwrite<char[]>(n);
g(x.get(), n);
return x;
}
static auto a(unsigned int n) noexcept -> std::vector<char>
{
auto x = h(n);
return std::vector(std::from_range, std::span(x.get(), n));
}
auto b(unsigned int n) noexcept -> std::vector<char>
{
auto y = a(n);
return std::vector(std::from_range, y);
}
```
I am less convinced that the same is true if we consider the function `a` and do not add the extra indirection through `b`, because in that case the lifetime of `x` overlaps that of the result. The potential issue I see is the guarantee of different pointer values being returned for overlapping allocations, and the pointer value being observable through `g`. Depending on the interpretation of [expr.new] I think the optimisation may nevertheless still be allowed. If the optimisation is possible in this case already, then that would of course be simpler and desirable.
Here is the example in the compiler explorer: [https://godbolt.org/z/fcjPz55aK](https://godbolt.org/z/fcjPz55aK)
</pre>
<img width="1" height="1" alt="" src="http://email.email.llvm.org/o/eJysVstu5LYS_Rr2pjCCRPVz0Yue9vS9RjazyN6gyJLEGYrUsKh-zNcHJcltx_YECRJAdgNi8dQ59ZQiso1H3IvVZ7F6WKghtSHuY2iVd6j8ogrmthdye4yBqA-U0EAKIFa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