# Push! to reshape-d vector unshares data with parent array

**URL:** <https://discourse.julialang.org/t/push-to-reshape-d-vector-unshares-data-with-parent-array/84664>\
**Category:** Internals & Design\
**Tags:** memory-allocation\
**Created:** [July 23, 2022, 6:17am UTC](https://discourse.julialang.org/t/push-to-reshape-d-vector-unshares-data-with-parent-array/84664 "2022-07-23T06:17:07Z")\
**Posts on this page:** 1\
**Showing post:** 9

<div class="post-metadata">

**Author:** ![Benny](https://avatars.discourse-cdn.com/v4/letter/b/49beb7/32.png) [@Benny](https://discourse.julialang.org/u/Benny)\
**Post date:** [July 24, 2022, 10:51am UTC](https://discourse.julialang.org/t/push-to-reshape-d-vector-unshares-data-with-parent-array/84664/9 "2022-07-24T10:51:12Z")

</div>

This does seem like an intentional design choice because `reshape`ing `Array`s does not use the wrapper `ReshapedArray`. However, consider these counterexamples to the two points of your understanding:

- The shared data error is not thrown if you made views or forced a `ReshapedArray`, even with the much more disruptive `insert!`. The `flags.how` protection might be limited to `Array`s.

```julia
julia> x = zeros(2); y = reshape(x, 1, 2)
1×2 Matrix{Float64}:
 0.0 0.0

julia> push!(x, 7.0)
ERROR: cannot resize array with shared data

julia> x = zeros(2); y = view(x, 1:1)
1-element view(::Vector{Float64}, 1:1) with eltype Float64:
 0.0

julia> push!(x, 7.0); insert!(x, 1, 1.0); y # y is corrupted!
1-element view(::Vector{Float64}, 1:1) with eltype Float64:
 1.0

julia> x = zeros(2); y = Base.ReshapedArray(x, (1,2), ())
1×2 reshape(::Vector{Float64}, 1, 2) with eltype Float64:
 0.0 0.0

julia> push!(x, 7.0); insert!(x, 1, 1.0); y # y is corrupted!
1×2 reshape(::Vector{Float64}, 1, 2) with eltype Float64:
 1.0 0.0

```

- When you `reshape` an `Array` to the same shape, you just reuse the instance, the ultimate sharing. Of course, `push!` does not reallocate. It could be a hassle to check whether `reshape` made a separate instance or not to keep the variables’ behavior consistent during mutations.

```julia
julia> x = zeros(2); y = reshape(x, 2);

julia> x === y
true

julia> push!(y, 7.0); x === y # x seems corrupted if you didn't check
true

```

---

_[View the full topic](https://discourse.julialang.org/t/push-to-reshape-d-vector-unshares-data-with-parent-array/84664)._
