2021年3月27日 星期六

Calling Convention in LLVM

Photo by Pavan Trikutam on Unsplash

Introduction

The calling convention is a specification which describes how parameters are passed to a function or how a return value is returned from a function. Different processor architectures may have different calling conventions. For example, in x86, function parameters would be put in the stack. In ARM, some of the function parameters would be put in the registers and the others would be put in the stack.

LLVM 是如何處理呼叫慣例(Calling Convention)

Photo by Quino Al on Unsplash

前言

所謂的呼叫慣例是指一個規範,這個規範描述了函式的參數如何傳遞、返回值式怎麼返回等等的議題。不同的處理器架構通常會有不同的呼叫慣例。比如: 在 x86 的架構中,函式的參數傳遞會以堆疊來完成。但在 Arm 的架構中,有一些參數會放在寄存器中,有一些參數則可能放在堆疊中。

2021年3月20日 星期六

[Effective C++] [閱讀心得]: 為何要使用前置宣告(Forward Declaration)

// A.h

class A { ... };

// B.h
#include "A.h"

class B {
...
private:
    A a;
...
};

上面這段程式碼中,由於 B 類別擁有 A 類別的成員變數,因此必須引入定義 A 類別的 A.h。然而,這樣做的缺點是,每當 A.h 內發生任何變動時,引入 B.h 的編譯單元也必須重新編譯。如果大型專案中存在著很多這樣的依賴關係的話,那麼專案的編譯時間就會變得很長。

2021年2月27日 星期六

[Effective C++] [閱讀心得]: 關於建構函式與解構函式

 為Base class宣告virtual的解構函式


class Base {
public:
    Base();
    ~Base();
    ...
};

class Derived : public Base { ... };

Base *getBase() { ... }

void foo() {
    Base *base = getBase();
    ...
    delete base;
}

這段程式碼中,getBase()回傳一個指標,此指標可能指向一個Base物件或是Derived物件。假設今天base指向了一個Derived的物件,那麼後面的delete base可能會導致物件無法完全銷毀的問題。

2021年2月20日 星期六

[Effective c++] [閱讀心得]: 條款13: 以對象管理資源

Photo by Alvaro Reyes on Unsplash

class A { ... };

void foo() {
    A a = new A;
    ...
    if (...) {
        delete a;
        return;
    }
    ...
    delete a;
    return;
}

如同上面的例子,因為if condition成立時foo()會提前return,所以必須在其中delete a,以免產生記憶體洩漏。
然而,這樣的撰寫風格其實具有極高的風險性。