Skip to content

Instantly share code, notes, and snippets.

@modularbot
Created April 24, 2024 14:59
Show Gist options
  • Save modularbot/c60ce97f28c5dcf04233aa601814c8e3 to your computer and use it in GitHub Desktop.
Save modularbot/c60ce97f28c5dcf04233aa601814c8e3 to your computer and use it in GitHub Desktop.
# Testing return value optimization
# Reading materials if you don't know what it is:
# https://blog.knatten.org/2011/08/26/dont-be-afraid-of-returning-by-value-know-the-return-value-optimization/
# https://stackoverflow.com/questions/12953127/what-are-copy-elision-and-return-value-optimization
# https://youtu.be/HNYOx-Vh_VA (Yes, I know this isn't "reading material")
struct DemoStruct(CollectionElement, Stringable):
var member1: Int
fn __init__(inout self, member1: Int):
self.member1 = member1
print("Called constructor for " + str(self))
fn __copyinit__(inout self, other: Self):
self.member1 = other.member1
print("Called copy constructor for " + str(self))
fn __moveinit__(inout self, owned other: Self):
self.member1 = other.member1
print("Called move constructor for " + str(self))
fn __del__(owned self):
print("Calling destructor for " + str(self))
fn __str__(self) -> String:
return "DemoStruct(" + str(self.member1) + ")"
fn add_10(param: DemoStruct) -> DemoStruct:
print("Entering add_10 function")
var return_value = DemoStruct(param.member1 + 10)
print("Exiting add_10 function")
return return_value
fn main():
var demo_obj_1 = DemoStruct(42)
var demo_obj_2 = add_10(
demo_obj_1
) # The move constructor for DemoStruct was called here
print("After calling add_10 function")
print(demo_obj_1)
print(demo_obj_2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment