0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【備忘録】C++ の output 引数で混乱しないための整理

0
Posted at

はじめに

C++ において、 GetX(input, output) のように

input / output を引数で分けるコードの場合、

T&T*T*& などがあり、混乱しました。

この記事では、備忘録として混乱しないように整理してまとめます。

3種類の引数

C++ の引数は、結局この3つしかありません。

書き方 名前
T 値渡し
T& 参照渡し
T* ポインタ渡し

値渡し(T):値のコピーが渡される

void f(int x);

参照渡し(T&, const T&):既存の変数の別名

void f(const T& in, T& out);

ポインタ渡し(T*, const T*):アドレスを渡す

void f(const T* in, T* out);

output 引数での型の違い:T& / T* / T*& / T**

T&:値を書き換える

void f(int& out) {
    out = 10;
}

T*:値をポインタ経由で書き換える

void f(int* out) {
    *out = 10;
}

T*&:ポインタを書き換える

void f(int*& out) {
    out = new int(10);
}

T**:ポインタをポインタ経由で書き換える

void f(int** out) {
    *out = new int(10);
}

感想

値渡しと参照渡しとポインタ渡しを理解したうえで、

何を書き換えているのか、といったことを意識すれば混乱しないと思いました。

0
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?