[過去ログ] プログラミング言語 Rust 4 (1002レス)
前次1-
抽出解除 レス栞

このスレッドは過去ログ倉庫に格納されています。
次スレ検索 歴削→次スレ 栞削→次スレ 過去ログメニュー
60
(1): 2017/10/30(月)22:54 ID:nDqoZaw+(1)調 AAS
ありがとう。
move するとアドレスが変わるというのは無理矢理実験したときに気付いたけれど、
実際はこんな感じで Box 化された構造体の特定の変数への参照が欲しかったので、
>>38が言った前スレの>>507-514辺りを見て、こんな感じで解決してました。

use std::mem;

struct Bar(i32);

struct Foo {
x: Box<Bar
x_ref: &'static i32,
}

impl Foo {
fn new() -> Self {
let mut foo = Foo {
x: Box::new(Bar(10)),
x_ref: unsafe { mem::uninitialized() },
};
let dummy = mem::replace(&mut foo.x_ref, unsafe { mem::transmute(&foo.x.0) } );
mem::forget(dummy);
foo
}
}
61: 2017/10/31(火)00:31 ID:pbuN/n26(1)調 AAS
>>60
ああ、確かにリファレンスとはいえ forget() しとくべきだね。
このコードについては↓でも問題ないけど、まあ実際の初期化はもっと他にも
処理があるだろうから、一般にはこううまくは行かなかいか。

struct Foo<'a> {
x: Box<Bar
x_ref: &'a i32,
}

impl<'a> Foo<'a> {
fn new() -> Self {
let x = Box::new(Bar(10));
Foo {
x_ref: unsafe { mem::transmute(&x.0) },
x: x,
}
}
}
前次1-
スレ情報 赤レス抽出 画像レス抽出 歴の未読スレ AAサムネイル

ぬこの手 ぬこTOP 0.042s