Skip to content

Commit

Permalink
to_address : イテレータからポインタへの変換例の追加
Browse files Browse the repository at this point in the history
  • Loading branch information
onihusube committed Feb 6, 2023
1 parent 6a2ea7c commit 44ce242
Showing 1 changed file with 38 additions and 1 deletion.
39 changes: 38 additions & 1 deletion reference/memory/to_address.md
Expand Up @@ -32,6 +32,9 @@ namespace std {
## 例
### ポインタの例
```cpp example
#include <iostream>
#include <memory>
Expand All @@ -55,12 +58,46 @@ int main()
```
* std::to_address[color ff0000]

### 出力
#### 出力
```
3
1
```

### イテレータの例

```cpp example
#include <iostream>
#include <vector>

int main()
{
std::vector<int> vec = {1, 2, 3, 4};

// vectorやstring等のイテレータはcontiguousではあるが、実装によってポインタではない場合がある
auto it = vec.begin();
auto end = vec.end();

// contiguousなイテレータをその要素へのポインタに変換する
int* p = std::to_address(it);

// 特に、終端イテレータからポインタへの変換で未定義動作を回避できる
int* ep = std::to_address(end);
// この様にしてしまうと、オブジェクトを指していないポインタのデリファレンスとなり未定義動作
//int* ep = &*end;

std::cout << *p << '\n';
std::cout << *(ep - 1);
}
```
* std::to_address[color ff0000]

#### 出力
```
1
4
```

## バージョン
### 言語
- C++20
Expand Down

0 comments on commit 44ce242

Please sign in to comment.