我一直认为在 std::shared_ptr
上使用 std::move()
会窃取指针并将原始指针设置为 nullptr
,因此不会增加引用计数。但在我的环境中似乎并非如此。
设置:
MacOS,g++ -version => "Apple LLVM version 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()
时引用计数会增加。
问题:
这是怎么回事?
_LIBCPP_HAS_NO_RVALUE_REFERENCES
未定义。 - Lightness Races in Orbit