今天学习一下Rust中的指针.
#ifndef ALGORITHM_MYCLASS_H
#define ALGORITHM_MYCLASS_H
#include <iostream>
using namespace std;
class MyClass
{
public:
char* p;
MyClass()
{
cout << "调用构造函数" << endl;
p = new char[1024 * 1024 * 100]();
}
~MyClass()
{
cout << "调用析构函数" << endl;
delete[] p;
}
};
#endif
int main(int argc, char *argv[]) {
{
vector<int> vec1{1, 2, 3};
unique_ptr<MyClass> myClass(new MyClass());
vector<int> vec2{1, 2, 3};
}
cin.get();
return 0;
}
进入正题,Rust中最典型的智能指针非Box和String莫属,String使用最多,Rust中的智能指针都会实现Drop(没实现Drop,不会自动释放资源,能叫智能)和Deref(没有*,能叫指针),在Rust中类型默认是分配栈上的,可以通过Box(有点像C#的装箱操作,在IL中使用box进行装箱操作)分配到堆上.具体看下面的示例代码:
fn main() {
{
let p1 = Point { x: 1 };
let point = Box::new(Point { x: 1 });
}
}
Box<T>源码,只有new/drop/deref.
#[lang = "owned_box"]
#[fundamental]
#[stable(feature = "rust1", since = "1.0.0")]
pub struct Box<T: ?Sized>(Unique<T>);
impl<T> Box<T> {
#[stable(feature = "rust1", since = "1.0.0")]
#[inline(always)]
pub fn new(x: T) -> Box<T> {
box x
}
}
#[stable(feature = "rust1", since = "1.0.0")]
unsafe impl<#[may_dangle] T: ?Sized> Drop for Box<T> {
fn drop(&mut self) {
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: ?Sized> Deref for Box<T> {
type Target = T;
fn deref(&self) -> &T {
&**self
}
}
通过Rust编译器rustc,生成汇编代码,是可以看到exchange_malloc函数的,具体看下边生成的代码:
rustc --emit asm .\test.rs
_ZN5alloc5alloc15exchange_malloc17h0cb71b2e0aa90f51E:
.seh_proc _ZN5alloc5alloc15exchange_malloc17h0cb71b2e0aa90f51E
subq $72, %rsp
.seh_stackalloc 72
.seh_endprologue
callq _ZN4core5alloc6layout6Layout25from_size_align_unchecked17hab6091c15e4a755eE
movq %rax, 48(%rsp)
movq %rdx, 40(%rsp)
leaq .L__unnamed_2(%rip), %rcx
movq 48(%rsp), %rdx
movq 40(%rsp), %r8
callq _ZN62_$LT$alloc..alloc..Global$u20$as$u20$core..alloc..AllocRef$GT$5alloc17h589e7297af27cd37E
movq %rdx, 64(%rsp)
movq %rax, 56(%rsp)
movq 56(%rsp), %rax
testq %rax, %rax
sete %cl
movzbl %cl, %edx
movl %edx, %eax
jne .LBB42_5
jmp .LBB42_7
.LBB42_7:
movq 48(%rsp), %rcx
movq 40(%rsp), %rdx
callq _ZN5alloc5alloc18handle_alloc_error17h96b5be050b7b98c9E
ud2
ud2
.LBB42_5:
movq 56(%rsp), %rcx
movq 64(%rsp), %rdx
callq _ZN4core3ptr8non_null26NonNull$LT$u5b$T$u5d$GT$10as_mut_ptr17h41487f386a6f2536E
movq %rax, 32(%rsp)
movq 32(%rsp), %rax
addq $72, %rsp
retq
.seh_handlerdata
.text
.seh_endproc
.def _ZN5alloc5alloc5alloc17ha8c49ddbf193d337E
.scl 3
.type 32
.endef
.p2align 4, 0x90
_ZN5alloc5alloc5alloc17ha8c49ddbf193d337E: