hblog
welcome here

魔禁之c++

user space context switch

#include <ucontext.h>
#include <iostream>

int main() {
    ucontext_t ctx;
    getcontext(&ctx);
    std::cout << "Hello, World!" << std::endl;
    setcontext(&ctx);
    return 0;
}

用户态下直接切换上下文。常用来实现协程。seastar里面用这玩意结合longjmpsetjmp实现了用户态的future线程库。因为ucontext_t这个struct太大的,所以用了diverse function。 不得不承认确实惊艳。

placement new

class Object;

typename std::aligned_storage<Object>::type obj;
new(&obj)Object(); // placement new
obj.~Object(); // relative call style of destructor

这个没啥说的。代码看多的基本都应该见过,就是用来栈上分配或节约内存的。

stack unwind

TODO

__attribute__

void dump(Object* o) { std::cout << obj << " is freed." << std::endl; }
{
    // `cleanup` attribute registers a function which will be call at the
    // end of the variable's life cycle. e.g. the following code dumps
    // a message when obj is out of the scope.
    Object obj __attribute__((cleanup(dump)));

    // TODO: more attributes
}