【发布时间】:2023-03-22 10:36:02
【问题描述】:
我正在研究一个二维向量(向量的向量)以在 C++ 中携带一些指针。
std::vector< std::vector<object*> > data;
这里的对象是一个类,每个数据条目都带有一个指向对象实例的指针。我让它在 C++ 中工作,但是当我将它应用到其他代码时,内存管理使它很难维护。我做了一些研究,有人建议改用智能指针。我尝试以下代码
#include <vector>
#include <memory>
using namespace std;
int main(void) {
vector< int > source = {1,2,3,4,5};
vector< auto_ptr<int> > co;
vector< vector< auto_ptr<int> > > all;
co.push_back( auto_ptr<int>(&source[0]) );
co.push_back( auto_ptr<int>(&source[2]) );
co.push_back( auto_ptr<int>(&source[4]) ); // it works well up to here
all.push_back(co); // but it crashs here
return 0;
}
其中一条错误消息是
C:/msys64/mingw64/include/c++/9.2.0/bits/stl_construct.h:75:7: 错误:没有匹配函数调用'std::auto_ptr::auto_ptr(const std::auto_ptr& )'
75 | { ::new(static_cast
我想知道如何将vector< auto_ptr<int> > 添加到另一个向量或列表中?
【问题讨论】:
-
使用
unique_ptr,而不是auto_ptr。这是语言有移动概念之前的残余。 (从技术上讲,是残留物,因为它现在已被移除。) -
“当我将内存管理应用到其他代码时,它很难维护” - 那么你的实际问题是什么?也许有更好的方法来解决它。
-
还要注意在运行时会出现问题,当
auto_ptr的析构函数会尝试删除source[0]、source[2]等。你应该只用一个指针初始化auto_ptr是单独分配的。