小编Car*_*son的帖子

如何创造一个已经解决的未来

我有一个返回std::future. 我已经在实现中添加了一个缓存,如果不需要重新计算,我想选择立即返回一个值。

我怎样才能创造一个已经解决的未来?

// Class declarations shortened to minimal example to communicate intent
class MyClass {
    Cache m_cache;

    std::future<int> foo(int arg);
}

class Cache {
    std::optional<int> get(int arg);
}

std::future<int> MyClass::foo(int arg) {
    if (auto res = m_cache.get(arg)) {
        // *res is my result
        return std::future(*res); // ????? Doesn't work
    }
    // If the cache misses, we need to calculate it
    // Fire up the ol' thread pool and get to work
    return std::launch(std::launch::async /* ommited for brevity …
Run Code Online (Sandbox Code Playgroud)

c++ c++11 stdasync std-future

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

如何将 `const std::vector&lt;T*&gt;` 转换为 `std::span&lt;const T*&gt;`

标题。

我正在实现这个类:

#include <span>
#include <vector>

class MyClass {
public:
    std::span<int *> numbers(void) {
        return m_numbers;
    }

    std::span<const int *> cnumbers(void) const {
        // What to do here?
    }

private:
    std::vector<int *> m_numbers;
};
Run Code Online (Sandbox Code Playgroud)

我的第一次尝试是使用非常量函数中展示的自动转换(我相信这与 相关std:decay?我不太明白)。

return m_numbers
Run Code Online (Sandbox Code Playgroud)

这无法编译,没有已知的转换。

我发现的一种实现是这样的:

return std::span(m_numbers.begin(), m_numbers.end());
Run Code Online (Sandbox Code Playgroud)

这会返回一个std::span<int * const>,但这并不完全是我想要的。这种使用的变体cbegin似乎没有帮助。

我的目标是 c++20

c++ std c++20 std-span

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

从文件读取原始结构的最佳方法

背景(可跳过)

在 Linux 上,该文件/var/run/utmp包含多个utmp结构,每个结构都是原始二进制格式,在一个文件中彼此跟随。utmp本身就比较大(我的机器上是384字节)。我正在尝试读取该文件的原始数据,并在数据有意义后实施检查。我对 Rust 并不陌生,但这是我第一次真正体验到事物不安全的一面。

问题陈述

我有一个包含多个 c 的文件sturct utmp文档)。在 Rust 中,我想将整个文件读入Vec<libc::utmpx>. 更具体地说,如果读者打开该文件,我该如何阅读struct utmp

到目前为止我所拥有的

下面是 的三种不同实现read_raw,它接受一个 reader 并返回一个RawEntry(我的 别名struct utmp)。哪种方法最正确?我正在尝试编写尽可能高性能的代码,并且我担心read_raw0如果涉及 memcpys,可能会比其他代码慢。完成此行为的最佳/最快方法是什么?

use std::io::Read;
use libc::utmpx as RawEntry;

const RawEntrySize = std::mem::size_of::<RawEntry>();
type RawEntryBuffer = [u8; RawEntrySize];

/// Read a raw utmpx struct
// After testing, this method doesn't work
pub fn read_raw0<R: Read>(reader: &mut R) -> …
Run Code Online (Sandbox Code Playgroud)

io unsafe rust

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

标签 统计

c++ ×2

c++11 ×1

c++20 ×1

io ×1

rust ×1

std ×1

std-future ×1

std-span ×1

stdasync ×1

unsafe ×1