让我们考虑下面的代码:
class A {
string a;
public A(string a) : a(a) { }
};
class B : public A {
public B(string a) : A(a) { }
};
int main() {
std::shared_ptr<A> x1 = std::make_shared<B>("x");
std::shared_ptr<A> x2 = std::make_shared<B>("x");
A* atom1 = x1.get();
A* atom2 = x2.get();
A* atom1X = std::make_shared<B>("x").get();
A* atom2X = std::make_shared<B>("x").get();
bool condition1 = (atom1 == atom2);
bool condition2 = (atom1X == atom2X);
}
Run Code Online (Sandbox Code Playgroud)
结果令我惊讶,因为条件 1 为假,但条件 2 为真。为什么?你能解释一下这是怎么回事吗?
我正在互联网上进行研究。我想了解它是如何工作的
A* atom1X = std::make_shared<B>("x").get(); // (1)
A* atom2X = std::make_shared<B>("x").get(); // (2)
Run Code Online (Sandbox Code Playgroud)
在这些定义中,std::make_share<B>("x")创建一个std::shared_ptr在完整表达式末尾(本质上是在下一个;)不再存在的临时值。这意味着这些指针所指向的对象在创建后立即被销毁。
当声明时,atom2X所指向的对象atom1X已被销毁并且其存储已被释放。碰巧的是,第 (1) 行中分配的对象先前占用的存储空间恰好适合容纳对象B,因此它在第 (2) 行中被重新使用。
本质上,如果删除所有智能指针,您可以认为您的代码与此等效:
A* x1 = new B("x");
A* x2 = new B("x");
A* atom1 = x1;
A* atom2 = x2;
A* atom1X = new B("x");
delete atom1X;
A* atom2X = new B("x");
delete atom2X;
Run Code Online (Sandbox Code Playgroud)