lifetime

Borrow-check error with variable not living long enough in nested lambda

妖精的绣舞 提交于 2019-12-04 03:38:48
I am getting an error inside a nested lambda. let rows = vec![ vec![3, 6, 2, 8, 9, 0], vec![0, 0, 1, 4, 5, 1], ]; let pair_sums = rows.iter() .flat_map(|row| { (0 ..= row.len()).map(|i| row[i] + row[i + 1]) }) .collect::<Vec<_>>(); println!("{:?}", pair_sums); error[E0597]: `row` does not live long enough --> src/main.rs:9:40 | 9 | (0..row.len() - 1).map(|i| row[i] + row[i + 1]) | --- ^^^ does not live long enough | | | capture occurs here 10 | }) | - borrowed value only lives until here 11 | .collect::<Vec<_>>(); | - borrowed value needs to live until here I can sort of see why this is

Lifetime of temporary bound to aggregate initialized struct member

大城市里の小女人 提交于 2019-12-04 02:14:09
Given the following code: class foo { }; class bar: public foo { public: ~bar() { printf("~bar()\n"); } }; class zab: public foo { public: ~zab() { printf("~zab()\n"); } }; struct foo_holder { const foo &f; }; int main() { foo_holder holder[]= { {bar()}, {zab()} }; printf("done!\n"); return 0; } the output is: ~bar() ~zab() done! C++0x has a clause that dictates this can create dangling references when used as a new initializer, but it says nothing (at least nothing I can find) about aggregate initialization of const references with temporaries. Is this unspecified behavior then? It isn't

How to resolve lifetime error for mutable reference in Rust?

放肆的年华 提交于 2019-12-04 01:58:05
问题 I am not sure why the following code does not compile. use std::cmp::Ordering; struct MyItr<'a> { cur: &'a i32, } impl<'a> Ord for MyItr<'a> { fn cmp(&self, other: &MyItr) -> Ordering { self.cur.cmp(&other.cur) } } impl<'a> PartialOrd for MyItr<'a> { fn partial_cmp(&self, other: &MyItr<'a>) -> Option<Ordering> { Some(self.cmp(other)) } } impl<'a> PartialEq for MyItr<'a> { fn eq(&self, other: &MyItr) -> bool { self.cur == other.cur } } impl<'a> Eq for MyItr<'a> {} fn f0<'a>(t0: &'a mut MyItr<

What is the “right” way to avoid Aliasing (e.g. when adding an element of a container to itself) in C++?

谁都会走 提交于 2019-12-04 01:16:39
std::vector<int> a; a.push_back(1); a.push_back(a[0]); I just learned that the code above can be very dangerous. (If it's not obvious why, you're not alone... it wasn't obvious to me either.) My questions: What is the "standard" way of dealing with it? Making a new variable and then assigning it immediately to something afterward seems a bit weird to me. Is there a better way of dealing with it? How do you train yourself to watch out for aliasing issues like this? What pattern(s) do you look for? I have no idea to recognize this situation; I only learned about aliasing when I learned about the

When an array is created by a subexpression, what happens with the temporaries therein?

大兔子大兔子 提交于 2019-12-03 22:44:11
I was reading these two paragraphs of the FDIS (12.2p{4,5}): There are two contexts in which temporaries are destroyed at a different point than the end of the full-expression. The first context is when a default constructor is called to initialize an element of an array. If the constructor has one or more default arguments, the destruction of every temporary created in a default argument is sequenced before the construction of the next array element, if any. and The second context is when a reference is bound to a temporary. The temporary to which the reference is bound or the temporary that

Mysterious lifetime issue while implementing trait for dyn object

独自空忆成欢 提交于 2019-12-03 22:34:57
Consider the following toy example: use std::cmp::Ordering; pub trait SimpleOrder { fn key(&self) -> u32; } impl PartialOrd for dyn SimpleOrder { fn partial_cmp(&self, other: &dyn SimpleOrder) -> Option<Ordering> { Some(self.cmp(other)) } } impl Ord for dyn SimpleOrder { fn cmp(&self, other: &dyn SimpleOrder) -> Ordering { self.key().cmp(&other.key()) } } impl PartialEq for dyn SimpleOrder { fn eq(&self, other: &dyn SimpleOrder) -> bool { self.key() == other.key() } } impl Eq for SimpleOrder {} This doesn't compile. It claims there is a lifetime issue in the implementation for partial_cmp :

Why doesn't my struct live long enough?

独自空忆成欢 提交于 2019-12-03 15:47:09
In Rust, I get the following error: <anon>:14:9: 14:17 error: `mystruct` does not live long enough <anon>:14 mystruct.update(); ^~~~~~~~ <anon>:10:5: 17:6 note: reference must be valid for the lifetime 'a as defined on the block at 10:4... <anon>:10 { <anon>:11 let initial = vec![Box::new(1), Box::new(2)]; <anon>:12 let mystruct = MyStruct { v : initial, p : &arg }; <anon>:13 <anon>:14 mystruct.update(); <anon>:15 ... <anon>:12:59: 17:6 note: ...but borrowed value is only valid for the block suffix following statement 1 at 12:58 <anon>:12 let mystruct = MyStruct { v : initial, p : &arg };

What does “Box<Fn() + Send + 'static>” mean in rust?

本小妞迷上赌 提交于 2019-12-03 12:27:52
What does Box<Fn() + Send + 'static> mean in rust? I stumbled upon this syntax while reading advanced types chapter. Send is a trait but what does it mean to + a lifetime to a trait ( 'static in this case) in type parametrization ? Also what is Fn() ? Masaki Hara Let's decompose it one-by-one. Box Box<T> is a pointer to heap-allocated T . We use it here because trait objects can only exist behind pointers. Trait objects In Box<Fn() + Send + 'static> , Fn() + Send + 'static is a trait object type. In future, it will be written Box<dyn (Fn() + Send + 'static)> to avoid confusion. Inside dyn are

Higher Ranked Trait Bound and boxed closures lifetime issue

核能气质少年 提交于 2019-12-03 06:44:20
I am trying to write a function returning a boxed closure that can work on references to types with any lifetime. When writing a specific instance, everything works fine. But when writing a generic version, I run into lifetime problems. struct Parameter<'a> { s: &'a str, } fn main() { let closure = generate_closure_gen(); let string = String::from("Hello World!"); let parameter = Parameter { s: &string }; // Error: string does not live long enough closure(&parameter); } // This one works fine // Desugared version for Box<Fn(&Parameter)> fn generate_closure() -> Box<for <'a, 'r> Fn(&'r

Safe to pass pointer to auto variable to function?

半腔热情 提交于 2019-12-03 05:24:42
Suppose I have a function that declares and initializes two local variables – which by default have the storage duration auto . This function then calls a second function, to which it passes the addresses of these two local variables. Can this second function safely use these pointers? A trivial programmatic example, to supplement that description: #include <stdio.h> int adder(int *a, int *b) { return *a + *b; } int main() { auto int a = 5; // `auto' is redundant; included for clarity auto int b = 3; // adder() gets the addresses of two auto variables! is this an issue? int result = adder(&a,