c++ - vector vector 的智能指针或常规指针

标签 c++ pointers vector

我想知道如果我对 vector 的 vector 使用智能指针是否会出现任何问题。我正在制作一个容器对象来保存派生对象(包括其他容器),我想使用智能指针进行 self 删除并想使用unique_ptr 用于单一所有权,但在这种情况下不能使用它。

每个容器都有一个大小,因此最后一个容器不能不包含第一个容器,这将防止我阅读 shared_pt 时出现的问题之一。

class Base{...}

class Item:public Base{...}

class Container : public Base{
    //int size;
    vector<shared_ptr<Base>>vec;
public:
     template <typename D>
     void AddItem(const D& thing) {
     vec.push_back(make_shared<D>(thing));
     }
};

Container bag;
Item thing;
Container bag2;

bag2.AddItem<Item>(thing);

bag.AddItem<Container>(bag2);

//_____________________________

相关,为什么这个不行

class Container :public Base{
vector<Base*>slot;
public:
~Container(){}

void Add(Base* thing){ slot.push_back(thing); }

void Delte_All()
{
    for(int i=0;i<slot.size();++i)
    {
        delete slot[i];
        cout << "Object " << i << " deleted" <<endl;
    }
    slot.clear();
}

};

int main()
{
Container bag;
Container bag2;
Base* thing=&bag2;

bag.Add(thing);

bag.Delte_All();

return 0;
}

最佳答案

  • 在您的第一个案例中,智能指针(例如 shared_ptr)没有问题。
    仅供引用,当您调用 make_shared<Item>(thing) , thing复制到堆上。

  • 在你的第二种情况下(使用原始指针), bag2是堆栈上的一个对象, 并且您不能删除分配在堆栈上的任何对象。 (*)

关于c++ - vector vector 的智能指针或常规指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24838072/

相关文章:

c++ - MVCC 实现中的无锁读写器同步

C++:一个 std::runtime_error 对象会在 longjmp 中泄漏吗?

pointers - MIPS 汇编指针到指针?

c++ - 数组而不是 vector 的 vector ,元素的 push_back()。 C++

c++ - 我如何将这些元素表达为 C++

c++ - 编译器计算错误

c++ - 将 <windows.h> 的函数与其他类混合使用是一种不好的做法吗?

c - 为什么将指向字符串的指针传递给函数时是 2 星

c - 动态分配结构体指针数组,指向它们并对它们进行排序

c++ - vector 元素输出垃圾