简体   繁体   English

当我使用引用而不是拥有的值调用 std::mem::drop 时会发生什么?

[英]What happens when I call std::mem::drop with a reference instead of an owned value?

fn main() {
    let k = "fire";

    drop(k);

    println!("{:?}", k);
}

Playground 操场

Why am I still able to use k after dropping it?为什么我删除后仍然可以使用k Does drop not deref a reference automatically? drop不会自动取消引用吗? If yes, then why?如果是,那为什么? What does the implementation of Drop look like for &str ? &strDrop实现是什么样的?

What happens when I call std::mem::drop with a reference当我使用引用调用std::mem::drop时会发生什么

The reference itself is dropped.引用本身被删除。

a reference instead of an owned value引用而不是拥有的值

A reference is a value.引用一个值。

Why am I still able to use k after dropping it?为什么我删除后仍然可以使用k

Because immutable pointers implement Copy .因为不可变指针实现了Copy You pass in a copy of the reference and it's dropped.您传入引用的副本,然后将其删除。

Does drop not deref a reference automatically? drop不会自动取消引用吗?

No, it does not.不,不是的。

what does the implementation of Drop look like for &str ? &strDrop实现是什么样的?

There isn't one for any kind of reference, immutable or mutable, so it's effectively 1 :没有任何类型的参考,不可变或可变的,所以它实际上是1

impl Drop for &str {
    fn drop(&mut self) {}
}

See also:也可以看看:


1 — As Peter Hall points out , there is a difference between having an empty Drop implementation and having no user-provided Drop implementation, but for the purposes of this question they are the same. 1 — 正如Peter Hall 所指出的,拥有空Drop实现和没有用户提供的Drop实现之间存在差异,但就问题而言,它们是相同的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Perl:当我们将常量值分配给参考变量而不是变量地址时会发生什么? - Perl: what happens when we assign a constant value to a reference variable instead of address of a variable? 当使用std :: forward时,为什么我可以在传入r值时调用l值引用函数? - When using std::forward, why am I able to call an l-value reference function while passing in an r-value? 当对象被删除时,引用会发生什么? - What happens to a reference when the object is deleted? 当函数的返回值是指针并且返回的类型是c ++中的引用时,会发生什么? - what happens when the function returning value is a pointer and the returning type is a reference in c++? 数组是通过引用传递的,但是,如果我仅传递未存储在内存中的数组的值,会发生什么? - Arrays are passed by reference, but what happens if I only pass the value of an array which is not stored in memory? 当我将子类作为抽象基类类型引用时会发生什么 - What happens when I make reference to subclass as a abstract base class type 如何在此C程序中使用按引用调用而不是按值调用? - How can I use call by reference instead of call by value in this C program? 当结构实例具有“引用类型”的属性时会发生什么? - What happens when a struct instance has a property that is a 'Reference Type?' 当您从 c++ function 返回引用时会发生什么? - What happens when you return a reference from a c++ function? 我可以将默认值传递给 std::string 的引用吗? - Can I pass a default value to a reference for a std::string ?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM