C++中向量元素的shared_ptr分割错误

Segmentation fault with shared_ptr of a vector element in C++

本文关键字:ptr 分割 错误 shared 向量 元素 C++      更新时间:2023-10-16

我是C++的新手,很难理解关系机制。我来自PHP背景,有数据库和ORM,我无法重现一个非常简单的案例。程序因"atomic.h"第49行{ return __atomic_fetch_add(__mem, __val, __ATOMIC_ACQ_REL); }中的分段错误而崩溃。这个问题来自shared_ptr,尽管我真的不知道如何使用智能指针(我已经阅读了数百篇文章和许多关于它们的问题,但仍然非常神秘)。

由于无法在存储库元素上创建工作指针,我试图在类之间建立一对多和多对一关系的尝试都以失败告终。我一定错过了什么,或者可能根本不是我们在C++中应该做的那样?

注意:我使用GCC6.3和C++17进行编译,只使用std,不使用boost。

class Car : public enable_shared_from_this<Car> {
//...
}
template <class Type>
class Repository<Type> {
vector<Type> collection;
public:
shared_ptr<Type> getNew() {
Type newType;
collection.push_back(newType);
return shared_ptr<Type>(&collection.back());
// I also tried this but program fails at this line although it compiles fine.
// return collection.back().shared_from_this();
}
}
class MainApp {
Repository<Cars> cars;
shared_ptr<Car> myCar;
public:
MainApp() {
myCar = cars.getNew();
}
}
int main() {
MainApp app; // OK - myCar points to the last car in cars repository
return 0; // SIGEGV Segmentation fault
}

TLDN'R:您应该在存储库中使用std::shared_ptr的向量,或者更改getNewCar以返回引用。

我对您的代码做了一些更改,使输出更加详细:

#include <memory>
#include <iostream>
#include <vector>
class Car
{
public:
Car()
{
std::cout << "Car ctor @" << this << std::endl;
}
Car(const Car& car)
{
std::cout << "Car copy ctor @" << this << " from " << &car << std::endl;
}
Car& operator=(const Car& car)
{
std::cout << "Car assign operator @" << this << std::endl;
}
~Car()
{
std::cout << "Car dtor @" << this << std::endl;
}
};
class Repository
{
std::vector<Car> collection;
public:
std::shared_ptr<Car> getNewCar()
{
Car newType;
collection.push_back(newType);
return std::shared_ptr<Car>(&collection.back());
}
};
int main()
{
Repository rep;
std::shared_ptr<Car> myCar = rep.getNewCar();
return 0;
}

代码结果为:

Car ctor @0x7ffe35557217
Car copy ctor @0x25b6030 from 0x7ffe35557217
Car dtor @0x7ffe35557217
Car dtor @0x25b6030
Car dtor @0x25b6030

你面临的问题是,你的代码在同一个对象上执行了两次Car析构函数,这可能会导致一些奇怪的行为,幸运的是,在你的情况下,这是一个Segmentation错误。

您在存储库中使用的std::vector负责在其对象被销毁时删除其所有对象。最后一个指向某个对象的"std::shared_ptr"也负责这样做

排队:

return shared_ptr<Type>(&collection.back());

获取当前属于std::vector的对象的地址,并使用指针创建std::shared_ptr。这个std::shared_ptr认为它是第一个跟踪对象的智能指针。因此,当它被销毁时(或者如果你制作了它的最后一个副本),这个对象析构函数将被调用。

因此,如果你相信汽车的寿命将比它来自的存储库更长:

class Repository
{
std::vector<std::shared_ptr<Car>> collection;
public:
std::shared_ptr<Car> getNewCar()
{
collection.push_back(std::shared_ptr<Car>(new Car()));
return collection.back();
}
};

如果您确信汽车将在存储库被销毁之前被销毁:

class Repository
{
std::vector<Car> collection;
public:
Car& getNewCar()
{
Car newCar;
collection.push_back(newCar);
return collection.back();
}
};