以下代码中shared_ptr<Point> sp3(sp1->addPoint(*sp2));执行拷贝构造还是移动构造?#include <memory> #include <iostream> using namespace std; class Point : public std::enable_shared_from_this<Point> { public: Point(int ix = 0, int iy = 0) : _ix(ix) , _iy(iy) { cout << "Point(int,int)" << endl; } ~Point() { cout << "~Point()" << endl; } shared_ptr<Point> addPoint(Point & pt) { _ix += pt._ix; _iy += pt._iy; return shared_from_this(); } private: int _ix; int _iy; }; void test() { shared_ptr<Point> sp1(new Point(1, 2)); shared_ptr<Point> sp2(new Point(11, 12)); shared_ptr<Point> sp3(sp1->addPoint(*sp2)); cout << "sp1.use_count = " << sp1.use_count() << endl; cout << "sp2.use_count = " << sp2.use_count() << endl; cout << "sp3.use_count = " << sp3.use_count() << endl; } int main() { test(); return 0; }
时间: 2024-04-02 08:37:50 浏览: 10
在这个代码中,执行的是拷贝构造。因为 addPoint 函数返回的是一个 shared_ptr 智能指针,而不是一个右值引用,所以 sp3 的初始化需要使用拷贝构造函数。拷贝构造函数会增加引用计数,因此 sp1 的引用计数为2。如果 addPoint 函数返回的是一个右值引用,那么就会执行移动构造函数,此时 sp1 的引用计数就是1。
相关问题
以下代码有什么问题? #include <iostream> #include <memory> using namespace std; class Point { public: Point(int ix = 0, int iy = 0): _ix(ix), _iy(iy) { cout << "Point(int,int)" << endl; } shared_ptr<Point> addPoint(Point & pt) { _ix += pt._ix; _iy += pt._iy; return shared_ptr<Point>(this); } ~Point() { cout << "~Point()" << endl; } private: int _ix; int _iy; }; int main() { shared_ptr<Point> sp(new Point(1, 2)); shared_ptr<Point> sp2(new Point(11, 12)); shared_ptr<Point> sp3(sp->addPoint(*sp2)); }
这段代码的问题是,`addPoint` 函数返回的是 `shared_ptr<Point>(this)`,这意味着返回的智能指针与函数内部创建的临时智能指针共享同一个对象,因此会导致内存泄漏。因为当 `addPoint` 函数返回时,临时智能指针会被销毁,从而导致指向这个对象的智能指针数量减少,但是由于返回的智能指针也指向这个对象,因此这个对象的引用计数不会减少,从而导致这个对象无法被销毁,造成内存泄漏。正确的做法是返回一个新创建的智能指针,如下所示:
```
shared_ptr<Point> addPoint(Point & pt) {
_ix += pt._ix;
_iy += pt._iy;
return shared_ptr<Point>(new Point(_ix, _iy));
}
```
以下代码为什么会double free? #include <iostream> #include <memory> using namespace std; class Point { public: Point(int ix = 0, int iy = 0): _ix(ix), _iy(iy) { cout << "Point(int,int)" << endl; } shared_ptr<Point> addPoint(Point & pt) { _ix += pt._ix; _iy += pt._iy; return shared_ptr<Point>(this); } ~Point() { cout << "~Point()" << endl; } private: int _ix; int _iy; }; int main() { shared_ptr<Point> sp(new Point(1, 2)); shared_ptr<Point> sp2(new Point(11, 12)); shared_ptr<Point> sp3(sp->addPoint(*sp2)); }
这段代码会导致 double free 的原因是在 Point 类的 addPoint 函数中返回了指向 this 的 shared_ptr 智能指针对象,导致了对象的所有权被多次转移,从而导致了重复释放对象内存的错误。
具体来说,在这段代码中,addPoint 函数返回的 shared_ptr 智能指针对象 sp3 持有了指向 this 的指针,也就是指向了 sp 指针所指向的 Point 类对象的内存。然而,在后面的代码中,sp 和 sp2 指针所指向的对象也都被用 shared_ptr 对象管理,因此当 sp 和 sp2 离开作用域时,它们会分别调用一次析构函数释放对象内存,但此时对象内存已经被 sp3 的所有权所持有,因此会导致 double free 的错误。
为了解决这个问题,可以将 addPoint 函数的返回类型改为 shared_ptr<Point>,然后通过调用 shared_ptr 的构造函数来创建一个新的 shared_ptr 智能指针对象,从而避免多次转移对象所有权导致的错误。