Skip to content

4.35. Raw Pointers #68

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Feb 14, 2016
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
97 changes: 61 additions & 36 deletions 1.6/ja/book/raw-pointers.md
Original file line number Diff line number Diff line change
@@ -1,36 +1,48 @@
% Raw Pointers
% 生ポインタ
<!-- % Raw Pointers -->

Rust has a number of different smart pointer types in its standard library, but
<!-- Rust has a number of different smart pointer types in its standard library, but
there are two types that are extra-special. Much of Rust’s safety comes from
compile-time checks, but raw pointers don’t have such guarantees, and are
[unsafe][unsafe] to use.
[unsafe][unsafe] to use. -->
Rustは標準ライブラリに異なるスマートポインタの型を幾つか用意していますが、更に特殊な型が2つあります。Rustの安全性の多くはコンパイル時のチェックに依るものですが、生ポインタを用いるとそういった保証が得られないため [unsafe][unsafe] です。

`*const T` and `*mut T` are called ‘raw pointers’ in Rust. Sometimes, when
<!-- `*const T` and `*mut T` are called ‘raw pointers’ in Rust. Sometimes, when
writing certain kinds of libraries, you’ll need to get around Rust’s safety
guarantees for some reason. In this case, you can use raw pointers to implement
your library, while exposing a safe interface for your users. For example, `*`
pointers are allowed to alias, allowing them to be used to write
shared-ownership types, and even thread-safe shared memory types (the `Rc<T>`
and `Arc<T>` types are both implemented entirely in Rust).

Here are some things to remember about raw pointers that are different than
other pointer types. They:

- are not guaranteed to point to valid memory and are not even
guaranteed to be non-null (unlike both `Box` and `&`);
- do not have any automatic clean-up, unlike `Box`, and so require
manual resource management;
- are plain-old-data, that is, they don't move ownership, again unlike
and `Arc<T>` types are both implemented entirely in Rust). -->
`*const T` と `*mut T` はRustにおいて「生ポインタ」と呼ばれます。時々、ある種ののライブラリを書く際に、あなたは何らかの理由でRustが行う安全性の保証を避けなければならないこともあります。このようなケースでは、ユーザに安全なインターフェースを提供しつつ、ライブラリの実装に生ポインタを使用できます。例えば、 `*` ポインタはエイリアスとして振る舞うこともできるので、所有権を共有する型を書くのに用いたり、スレッドセーフな共有メモリ型でさえも実装できます。( `Rc<T>` と `Arc<T>` 型は完全にRustのみで実装されています)

<!-- Here are some things to remember about raw pointers that are different than
other pointer types. They: -->
以下は覚えておくべき生ポインタとその他のポインタ型との違いです。

<!-- - are not guaranteed to point to valid memory and are not even
guaranteed to be non-null (unlike both `Box` and `&`); -->
<!-- - do not have any automatic clean-up, unlike `Box`, and so require
manual resource management; -->
<!-- - are plain-old-data, that is, they don't move ownership, again unlike
`Box`, hence the Rust compiler cannot protect against bugs like
use-after-free;
- lack any form of lifetimes, unlike `&`, and so the compiler cannot
use-after-free; -->
<!-- - lack any form of lifetimes, unlike `&`, and so the compiler cannot
reason about dangling pointers; and
- have no guarantees about aliasing or mutability other than mutation
not being allowed directly through a `*const T`.
not being allowed directly through a `*const T`. -->
- 有効なメモリを指していることが保証されないどころか、nullでないことも保証されない( `Box` と `&` では保証される)
- `Box` とは異なり、自動的な後処理が一切行われないため、手動のリソース管理が必要
- plain-old-dataであるため、Rustコンパイラはuse-after-freeのようなバグから保護できない
- `&` と異なり、ライフタイムの機能が無効化されるため、コンパイラはダングリングポインタを推論できない
- また、 `*const T` を直接介した変更は拒むが、それ以外のエイリアシングやミュータビリティに関する保証はない

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[markdown]
ごめんなさい、レビュー漏れてました。リストアイテムの間にコメントを挟むと正しくレンダリングされないのでこちら、リスト全体をコメントアウトしてその下に訳を置くようお願いします。

# Basics

Creating a raw pointer is perfectly safe:
<!-- # Basics -->
# 基本

<!-- Creating a raw pointer is perfectly safe: -->
生ポインタを作成すること自体は絶対に安全です。

```rust
let x = 5;
Expand All @@ -40,7 +52,9 @@ let mut y = 10;
let raw_mut = &mut y as *mut i32;
```

However, dereferencing one is not. This won’t work:
<!-- However, dereferencing one is not. This won’t work: -->
しかしながら参照外しは安全ではありません。以下は動作しないでしょう。


```rust,ignore
let x = 5;
Expand All @@ -49,16 +63,18 @@ let raw = &x as *const i32;
println!("raw points at {}", *raw);
```

It gives this error:
<!-- It gives this error: -->
このコードは以下のエラーが発生します。

```text
error: dereference of raw pointer requires unsafe function or block [E0133]
println!("raw points at {}", *raw);
^~~~
```

When you dereference a raw pointer, you’re taking responsibility that it’s not
pointing somewhere that would be incorrect. As such, you need `unsafe`:
<!-- When you dereference a raw pointer, you’re taking responsibility that it’s not
pointing somewhere that would be incorrect. As such, you need `unsafe`: -->
生ポインタを参照外しする時、ポインタが間違った場所を指していないことに対して責任を負うことになります。そういう時は、 `unsafe` を付けなければなりません。

```rust
let x = 5;
Expand All @@ -69,43 +85,51 @@ let points_at = unsafe { *raw };
println!("raw points at {}", points_at);
```

For more operations on raw pointers, see [their API documentation][rawapi].
<!-- For more operations on raw pointers, see [their API documentation][rawapi]. -->
生ポインタの操作に関する詳細は、 [APIドキュメント][rawapi] を参照してください。

[unsafe]: unsafe.html
[rawapi]: ../std/primitive.pointer.html

# FFI

Raw pointers are useful for FFI: Rust’s `*const T` and `*mut T` are similar to
<!-- Raw pointers are useful for FFI: Rust’s `*const T` and `*mut T` are similar to
C’s `const T*` and `T*`, respectively. For more about this use, consult the
[FFI chapter][ffi].
[FFI chapter][ffi]. -->
生ポインタはFFIを使う際に役立ちます。Rustの `*const T` と `*mut T` はそれぞれC言語の `const T*` と `T*` に似ているからです。これの使い方に関する詳細は、 [FFIの章][ffi] を参照してください。

[ffi]: ffi.html

# References and raw pointers
<!-- # References and raw pointers -->
# 参照と生ポインタ

At runtime, a raw pointer `*` and a reference pointing to the same piece of
<!-- At runtime, a raw pointer `*` and a reference pointing to the same piece of
data have an identical representation. In fact, an `&T` reference will
implicitly coerce to an `*const T` raw pointer in safe code and similarly for
the `mut` variants (both coercions can be performed explicitly with,
respectively, `value as *const T` and `value as *mut T`).
respectively, `value as *const T` and `value as *mut T`). -->
実行時において、同じデータを指す生ポインタ `*` と参照は内部的に同一です。事実、 `unsafe` 外の安全なコードにおいて `&T` 参照は `*const T` 生ポインタへ暗黙的に型強制されますし、 `mut` の場合でも同様です。(これら型強制は、それぞれ `value as *const T` と `value as *mut T` のように、明示的に行うこともできます。)

Going the opposite direction, from `*const` to a reference `&`, is not safe. A
<!-- Going the opposite direction, from `*const` to a reference `&`, is not safe. A
`&T` is always valid, and so, at a minimum, the raw pointer `*const T` has to
point to a valid instance of type `T`. Furthermore, the resulting pointer must
satisfy the aliasing and mutability laws of references. The compiler assumes
these properties are true for any references, no matter how they are created,
and so any conversion from raw pointers is asserting that they hold. The
programmer *must* guarantee this.
programmer *must* guarantee this. -->
逆に、 `*const` から 参照 `&` へ遡るのは安全ではありません。 `&T` は常に有効であるため、最低でも `*const T` は型 `T` の有効な実体を指さなければならないのです。その上、ポインタは参照のエイリアシングとミュータビリティの規則も満たす必要があります。コンパイラはあらゆる参照についてこれらの性質が真であると仮定しており、その生成方法に依らず適用するため、生ポインタからのいかなる変換も、参照先の値が上記の性質を満たすと表明していることになります。プログラマがこのことを保証 *しなければならない* のです。

The recommended method for the conversion is:
<!-- The recommended method for the conversion is: -->
おすすめの変換の方法は以下のとおりです。
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[markdown]
ブロックコードの前に一行空行を空けないと正しくレンダリングされないので空行をお願いします。


```rust
// explicit cast
# // explicit cast
// 明示的キャスト
let i: u32 = 1;
let p_imm: *const u32 = &i as *const u32;

// implicit coercion
# // implicit coercion
// 暗黙的キャスト
let mut m: u32 = 2;
let p_mut: *mut u32 = &mut m;

Expand All @@ -115,7 +139,8 @@ unsafe {
}
```

The `&*x` dereferencing style is preferred to using a `transmute`. The latter
<!-- The `&*x` dereferencing style is preferred to using a `transmute`. The latter
is far more powerful than necessary, and the more restricted operation is
harder to use incorrectly; for example, it requires that `x` is a pointer
(unlike `transmute`).
(unlike `transmute`). -->
`&*x` 参照外し方式は `transmute` を用いるよりも好ましいです。後者は必要以上に強力ですから、より用途が限定されている操作の方が間違って使いにくいでしょう。例えば、前者の方法は `x` がポインタである必要があります。( `transmute` とは異なります)