tac
tac
Explore posts from servers
MModular
Created by tac on 9/12/2023 in #questions
__moveinit__ and __del__
When the __del__ method is not implemented, the __moveinit__ method is less likely to be invoked. Why is this the case? Consider the following example code:
struct Pair:
var x: Int
var y: Int

fn __init__(inout self, x: Int, y: Int):
print("Running init")
self.x = x
self.y = y

fn __moveinit__(inout self, owned existing: Self):
print("move init")
self.x = existing.x
self.y = existing.x

fn __copyinit__(inout self, existing: Self):
print("copy init")
self.x = existing.x
self.y = existing.y

fn copy(owned pair: Pair) -> Pair:
return pair

fn main():
let p = Pair(1, 2)
let moved = copy(p^)
let moved2 = moved^
struct Pair:
var x: Int
var y: Int

fn __init__(inout self, x: Int, y: Int):
print("Running init")
self.x = x
self.y = y

fn __moveinit__(inout self, owned existing: Self):
print("move init")
self.x = existing.x
self.y = existing.x

fn __copyinit__(inout self, existing: Self):
print("copy init")
self.x = existing.x
self.y = existing.y

fn copy(owned pair: Pair) -> Pair:
return pair

fn main():
let p = Pair(1, 2)
let moved = copy(p^)
let moved2 = moved^
On execution, the output is:
copy init
move init
copy init
move init
However, when we include the __del__ method as follows:
struct Pair:
# omitted
fn __del__(owned self):
print("deleted")

fn copy(owned pair: Pair) -> Pair:
return pair

fn main():
let p = Pair(1, 2)
let moved = copy(p^)
let moved2 = moved^
struct Pair:
# omitted
fn __del__(owned self):
print("deleted")

fn copy(owned pair: Pair) -> Pair:
return pair

fn main():
let p = Pair(1, 2)
let moved = copy(p^)
let moved2 = moved^
The output changes to:
move init
move init
deleted
move init
move init
deleted
The presence or absence of the __del__ method impacts the sequence of method calls __copyinit__ and __moveinit__, potentially affecting the performance. Why does this occur?
14 replies