Discussion: https://github.com/JuliaLang/julia/issues/12441
On Thursday, July 21, 2016 at 2:49:19 PM UTC-4, gTcV wrote: > > I recently frequently encounter the situation where I need to both copy as > well as optionally convert an object. It turns out `convert` on its own > will not do the job in this case as it doesn't create a copy if the > conversion is trivial: > > julia> v = Vector{Int}(); > julia> convert(Vector{Int}, v) === v > true > julia> convert(Vector{Float64}, v) === v > false > > So to be safe I have to write `copy(convert(NewT,obj))`, but that creates > two copies in case `NewT != obj` [1]. I assume this must be a fairly common > problem, and I am surprised Julia doesn't offer a solution to it. > > The following is a first attempt at a solution, but I would not be > surprised if there are edge cases where this approach fails. > > function copyconvert{T}(::Type{T}, x) > y = convert(T,x) > if y === x > return copy(x) > else > return y > end > end > > [1] In C++, the compiler would optimise this case down to one copy ("copy > elision"), but I assume the Julia compiler doesn't. Correct? >