Fre*_*Man 9 syntax operators placement-new rust
<-Rust中的运算符/表达式是什么?你可以在这里找到符号.
我碰巧在查看描述Rust中表达式和操作的页面.我没有在Rust中编程,所以我问了一个朋友谁是亲Rust这个符号是什么,但即使他不知道它是什么.
Pet*_*all 12
该<-运营商是不是稳定的锈的一部分.至少还没有.
有一个RFC提出<-了将新对象直接写入内存中特定位置的语法,作为另一个提出的RFC的替代方案in.这是(当前不稳定的)box语法的概括,它允许您直接分配给堆,而无需临时堆栈分配.
目前,没有使用unsafe代码就没有办法做到这一点,通常你需要先在堆栈上进行分配.有一个关于RFC的基本问题的讨论,它是相关RFC链中的第一个,并给出了背景动机,但关键原因是:
在C++中,有一个名为"placement new"的功能,它通过让你提供一个参数来实现这一点,该参数new是一个开始写入的现有指针.例如:
// For comparison, a "normal new", allocating on the heap
string *foo = new string("foo");
// Allocate a buffer
char *buffer = new char[100];
// Allocate a new string starting at the beginning of the buffer
string *bar = new (buffer) string("bar");
Run Code Online (Sandbox Code Playgroud)
从我可以收集的内容来看,上面的C++示例在Rust中可能看起来像这样<-:
// Memory allocated on heap (with temporary stack allocation in the process)
let foo = Box::new(*b"foo");
// Or, without the stack allocation, when box syntax stabilises:
let foo = box *b"foo";
// Allocate a buffer
let mut buffer = box [0u8; 100];
// Allocate a new bytestring starting at the beginning of the buffer
let bar = buffer[0..3] <- b"bar";
Run Code Online (Sandbox Code Playgroud)
我不希望这个确切的代码按原样编译,即使实现了放置功能.但请注意,Rust目前无法完成最后一行尝试的操作:b"bar"直接在缓冲区的开头分配,而不先在堆栈上进行分配.在Rust现在,没有办法做到这一点.即使unsafe代码也没有帮助你.您仍然必须首先在堆栈上分配,然后将其克隆到缓冲区:
// Note that b"bar" is allocated first on the stack before being copied
// into the buffer
buffer[0..3].clone_from_slice(&b"bar"[0..3]);
let bar = &buffer[0..3];
Run Code Online (Sandbox Code Playgroud)
和box语法不会帮助这里无论是.这将分配新的堆内存,然后您仍然必须将数据复制到缓冲区.
对于在堆上分配新对象时避免临时堆栈分配的简单情况,box语法将在稳定时解决.Rust将需要在将来的某个时刻解决更复杂的案例,但尚不确定<-是否会出现这种语法.