我阅读以下通过文章安东尼威廉姆斯和我除了理解为原子共享计数std::shared_ptr在std::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) 为什么Rust中不允许使用此语法:
fn main() {
let a = String::from("ping");
let b = a;
println!("{{{}, {}}}", a, b);
}
Run Code Online (Sandbox Code Playgroud)
当我尝试编译这段代码时,我得到了:
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
实际上,我们可以简单地创建一个引用 - 在运行时它是不一样的:
fn main() {
let a = String::from("ping"); …Run Code Online (Sandbox Code Playgroud)