I’ve seen it used in programming (specifically in the C++ domain) and have no idea what it is. Presumably it is a design pattern, but I could be wrong. Can anyone give a good example of a thunk?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
A
thunkusually refers to a small piece of code that is called as a function, does some small thing, and thenJUMPs to another location (usually a function) instead of returning to its caller. Assuming the JUMP target is a normal function, when it returns, it will return to the thunk’s caller.Thunks can be used to implement lots of useful things efficiently
protocol translation — when calling from code that uses one calling convention to code that uses a different calling convention, a
thunkcan be used to translate the arguments appropriately. This only works if the return conventions are compatible, but that is often the casevirtual function handling — when calling a virtual function of a multiply-inherited base class in C++, there needs to be a fix-up of the
thispointer to get it to point to the right place. Athunkcan do this.dynamic closures — when you build a dynamic closure, the closure function needs to be able to get at the context where it was created. A small
thunkcan be built (usually on the stack) which sets up the context info in some register(s) and then jumps to a static piece of code that implements the closure’s function. The thunk here is effectively supplying one or more hidden extra arguments to the function that are not provided by the call site.