我对std :: move函数有疑问。请参考下面的代码:
#include <iostream>
#include <memory>
using namespace std;
class CPointer {
public:
CPointer(double a, double b)
{
m_dX = a;
m_dY = b;
}
~CPointer()
{
m_dX = m_dY = 0;
}
double getX() const
{return m_dX;}
double getY() const
{return m_dY;}
private:
double m_dX;
double m_dY;
};
class CContainer
{
public:
CContainer(CPointer* p)
{
m_p = p;
}
~CContainer()
{
m_p = nullptr;
}
CPointer* getP() const
{return m_p;}
private:
CPointer* m_p;
};
class CBigContainer
{
public:
CBigContainer(CContainer* p)
{
m_p = p;
}
~CBigContainer()
{
m_p = nullptr;
}
CContainer* getP() const
{return m_p;}
private:
CContainer* m_p;
};
int main()
{
CPointer* pPointer = new CPointer(150,360);
cout << "1.) " << pPointer->getX() << " , " << pPointer->getY() << "\n";
std::shared_ptr<CContainer> spContainer = std::make_shared<CContainer>(pPointer);
cout << "2.) " << pPointer->getX() << " , " << pPointer->getY() << "\n";
std::shared_ptr<CBigContainer> spBigContainer = std::make_shared<CBigContainer>(std::move(spContainer.get())); //<--- std::move here
cout << "3.) " << spBigContainer->getP()->getP()->getX() << " , " << spBigContainer->getP()->getP()->getY() << "\n";
cout << "4.) " << spContainer->getP()->getX() << " , " << spContainer->getP()->getY() << "\n";
cout << "5.) " << pPointer->getX() << " , " << pPointer->getY() << "\n";
return 0;
}
这就是结果:
我的问题是,我正在使用std :: move
std::shared_ptr<CBigContainer> spBigContainer = std::make_shared<CBigContainer>(std::move(spContainer.get()));
因此,我希望在代码行之后不能使用spContainer,因为已删除了智能指针中的对象。但是它仍然可以正常工作。在这种情况下,不使用std :: move似乎没有什么不同。
您能详细给我解释一下吗?非常感谢。
因此,我希望在代码行之后不能使用spContainer,因为智能指针内的对象已删除。
您的代码从不实际请求任何移动操作。智能指针是红色鲱鱼,在这种情况下,您可以看到相同的行为:
CContainer a(pPointer);
CBigContainer b(std :: move(&a));
最后一行与CBigContainer b( &a );
相同,因为CBigContainer
的构造函数接受一个指针,并且基本类型(包括指针)的移动操作的行为是使源保持不变。
您的代码使CBigContainer
对象指向CContainer
对象(后者仍由智能指针管理)。这是一个坏主意,因为如果您随后释放CContainer
智能指针,则CBigContainer
指向它的指针将悬垂。
您的CContainer
和CBigContainer
对象持有指向其他对象的原始指针。将这些对象放在智能指针中不会对此进行更改。
如果您不清楚,这是两件事:
第一个将智能指针留空。第二个使智能指针处于活动状态并管理处于移动后状态的对象。
这是将移出spContainer的代码示例:
std::shared_ptr<CContainer> other = std::move(spContainer);
这将调用移动操作,因为左侧的shared_ptr
具有移动构造器它接受另一个与参数相同类型的shared_ptr
。