相关疑难解决方法(0)

std :: shared_ptr和std :: experimental :: atomic_shared_ptr有什么区别?

我阅读以下通过文章安东尼威廉姆斯和我除了理解为原子共享计数std::shared_ptrstd::experimental::atomic_shared_ptr实际指针到共享对象也是原子?

但是,当我读到的引用计数的版本lock_free_stack在安东尼的书中描述了关于C++并发似乎对我来说,同样aplies也是std::shared_ptr,因为功能,如std::atomic_load,std::atomic_compare_exchnage_weak被应用到的实例std::shared_ptr.

template <class T>
class lock_free_stack
{
public:
  void push(const T& data)
  {
    const std::shared_ptr<node> new_node = std::make_shared<node>(data);
    new_node->next = std::atomic_load(&head_);
    while (!std::atomic_compare_exchange_weak(&head_, &new_node->next, new_node));
  }

  std::shared_ptr<T> pop()
  {
    std::shared_ptr<node> old_head = std::atomic_load(&head_);
    while(old_head &&
          !std::atomic_compare_exchange_weak(&head_, &old_head, old_head->next));
    return old_head ? old_head->data : std::shared_ptr<T>();
  }

private:
  struct node
  {
    std::shared_ptr<T> data;
    std::shared_ptr<node> next;

    node(const T& data_) : data(std::make_shared<T>(data_)) {} …
Run Code Online (Sandbox Code Playgroud)

c++ concurrency smart-pointers atomic c++11

21
推荐指数
3
解决办法
6909
查看次数

什么是C++的shared_ptr的Rust等价物?

为什么Rust中不允许使用此语法:

fn main() {
    let a = String::from("ping");
    let b = a;

    println!("{{{}, {}}}", a, b);
}
Run Code Online (Sandbox Code Playgroud)

当我尝试编译这段代码时,我得到了:

error[E0382]: use of moved value: `a`
 --> src/main.rs:5:28
  |
3 |     let b = a;
  |         - value moved here
4 | 
5 |     println!("{{{}, {}}}", a, b);
  |                            ^ value used here after move
  |
  = note: move occurs because `a` has type `std::string::String`, which does not implement the `Copy` trait
Run Code Online (Sandbox Code Playgroud)

实际上,我们可以简单地创建一个引用 - 在运行时它是不一样的:

fn main() {
    let a = String::from("ping"); …
Run Code Online (Sandbox Code Playgroud)

scope shared-ptr ownership rust

2
推荐指数
2
解决办法
1222
查看次数

标签 统计

atomic ×1

c++ ×1

c++11 ×1

concurrency ×1

ownership ×1

rust ×1

scope ×1

shared-ptr ×1

smart-pointers ×1