小编Jon*_*eck的帖子

std :: move返回weak_ptr :: lock的返回值搞乱了shared_ptr的引用计数?

我需要解释以下行为:

#include <iostream>
#include <memory>
#include <vector>

struct A {
    std::string s = "foo";
    std::weak_ptr<A> h;
    std::shared_ptr<A> && getR() {
        return std::move(h.lock());
    }
    std::shared_ptr<A> getL() {
        return h.lock();
    }
};

std::vector< std::shared_ptr<A> > storage;
std::vector< std::weak_ptr<A> > accountant;

void store(std::shared_ptr<A> && rr) {
    std::cout << "store '" << rr->s << "' uses: " << rr.use_count() << std::endl;
    storage.push_back(std::move(rr));
}

int main() {
    // create keeper of A
    auto keeper = std::make_shared<A>();
    keeper->s = "bar";
    // store weak_ptr-type handle with accountant …
Run Code Online (Sandbox Code Playgroud)

c++ shared-ptr weak-ptr c++11 c++14

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

标签 统计

c++ ×1

c++11 ×1

c++14 ×1

shared-ptr ×1

weak-ptr ×1