小编Mok*_*sha的帖子

Rc 依赖循环的最小示例是什么?

我正在尝试编写一个 Rust 程序,该程序由于带有引用计数的循环而泄漏内存。下面的示例看起来应该会导致内存泄漏,但根据 Valgrind 的说法,它不会泄漏内存。是什么赋予了?

test.rs

use std::cell::RefCell;
use std::rc::Rc;

struct Foo {
    f: Rc<Bar>,
}

struct Bar {
    b: RefCell<Option<Rc<Foo>>>,
}

fn main() {
    let bar = Rc::new(Bar {
        b: RefCell::new(None),
    });
    let foo = Rc::new(Foo { f: bar.clone() });
    *bar.b.borrow_mut() = Some(foo.clone());
}
Run Code Online (Sandbox Code Playgroud)

Valgrind 输出:

use std::cell::RefCell;
use std::rc::Rc;

struct Foo {
    f: Rc<Bar>,
}

struct Bar {
    b: RefCell<Option<Rc<Foo>>>,
}

fn main() {
    let bar = Rc::new(Bar {
        b: RefCell::new(None),
    });
    let foo = …
Run Code Online (Sandbox Code Playgroud)

valgrind memory-leaks rust

5
推荐指数
1
解决办法
662
查看次数

0除以无穷大保证为0?

根据这个问题,n/inf预计将为零n != 0.什么时候n == 0?根据IEEE-754,(0 / inf) == 0总是如此吗?

c++ ieee-754

3
推荐指数
1
解决办法
1388
查看次数

误解List monad

我很困惑为什么我的程序得到以下输出:

-- test.hs

f :: Int -> [[Int]]
f 0 = []
f x = do
  y <- [0, 1]
  g <- f (x - 1)
  return (y : g)

main :: IO ()
main = print $ f 2
Run Code Online (Sandbox Code Playgroud)

我希望这个程序的输出是

[[0, 0], [0, 1], [1, 0], [1, 1]]
Run Code Online (Sandbox Code Playgroud)

但是,我得到的只是

$ ghc -o test test.hs && ./test
[]
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?

monads haskell

1
推荐指数
1
解决办法
112
查看次数

命名空间限定'运算符=='的重载

我很好奇以下为什么不编译:

#include <iostream>
#include <functional>

namespace Bar {
struct Foo {
  int x;
};
}  // Namespace                                                                                                                     

static bool operator==(const Bar::Foo& a, const Bar::Foo& b) {
  return a.x == b.x;
}

int main() {
  Bar::Foo a = { 0 };
  Bar::Foo b = { 1 };

  // The following line is OK
  std::cout << (a == b) << std::endl;

  // The following line is not OK
  std::cout << std::equal_to<Bar::Foo>()(a, b) << std::endl;
}
Run Code Online (Sandbox Code Playgroud)

在这种情况下编译器barfs:

[test]$ g++ --std=c++11 -o test test.cc …
Run Code Online (Sandbox Code Playgroud)

c++ argument-dependent-lookup c++11

1
推荐指数
1
解决办法
110
查看次数

线程引用需要静态生存期?

虽然直觉上传递给生成的线程的引用需要具有静态生命周期,但我不清楚究竟是什么使得以下代码无法编译:

use std::sync::Arc;
use std::sync::Mutex;

struct M;

fn do_something(m : Arc<Mutex<&M>>) {
    println!("Ha, do nothing!");
}

fn main() {
    let a = M;
    {
        let c : Arc<Mutex<&M>> = Arc::new(Mutex::new(&a));
        for i in 0..2 {
            let c_clone = c.clone();
            ::std::thread::spawn(move || do_something(c_clone));
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

编译这个小程序会出现以下错误:

$ rustc -o test test.rs
test.rs:13:55: 13:56 error: `a` does not live long enough
test.rs:13         let c : Arc<Mutex<&M>> = Arc::new(Mutex::new(&a));
                                                             ^
note: reference must be valid for the static lifetime...
Run Code Online (Sandbox Code Playgroud)

在我看来,变量a将会超出现实 …

multithreading lifetime rust

1
推荐指数
1
解决办法
613
查看次数