【发布时间】:2020-01-11 02:44:34
【问题描述】:
我一直假设std::shared_ptr 上的std::move() 窃取指针并将原始指针设置为nullptr - 因此不会增加引用计数。在我的世界里,这似乎不是真的。
设置:
MacOS, g++ -version => "Apple LLVM 版本 10.0.1 (clang-1001.0.46.3)"
代码:
#include <cstdio>
#include <memory>
class Thing { public: Thing(int N) : value(N) {} int value; };
void print(const char* name, std::shared_ptr<Thing>& sp)
{ printf("%s: { use_count=%i; }\n", name, (int)sp.use_count()); }
int main(int argc, char** argv) {
std::shared_ptr<Thing> x(new Thing(4711));
print("BEFORE x", x);
std::shared_ptr<Thing> y = std::move(x);
y->value = 4712;
print(" AFTER x", x);
print(" AFTER y", y);
return 0;
}
输出:
编译 (g++ tmp.cpp -o test),运行 (./test),交付
BEFORE x: { use_count=1; }
AFTER x: { use_count=2; }
AFTER y: { use_count=2; }
因此,使用std::move() 时引用计数会增加。
问题:
这是怎么回事?
【问题讨论】:
-
修复 UB can't reproduce.
-
FWIW 我(几乎)使用相同的版本,并且库代码与报告不匹配 iff
_LIBCPP_HAS_NO_RVALUE_REFERENCES未定义
标签: c++ macos shared-ptr rvalue-reference