在STL向量中存储对象 - 最小的方法集

问题描述 投票:6回答:3

什么是复杂对象的“最小框架”(必要的方法)(具有显式的malloced内部数据),我想将其存储在STL容器中,例如<vector>

对于我的假设(复杂对象Doit的例子):

#include <vector>
#include <cstring>
using namespace std;
class Doit {
    private:
        char *a;
    public:
        Doit(){a=(char*)malloc(10);}
        ~Doit(){free(a);}
};

int main(){
    vector<Doit> v(10);
}

*** glibc detected *** ./a.out: double free or corruption (fasttop): 0x0804b008 ***
Aborted

在valgrind:

malloc/free: 2 allocs, 12 frees, 50 bytes allocated.

更新:

这种对象的最小方法是:(基于sbi答案)

class DoIt{
    private:
        char *a;
    public:
        DoIt() { a=new char[10]; }
        ~DoIt() { delete[] a; }
        DoIt(const DoIt& rhs) { a=new char[10]; std::copy(rhs.a,rhs.a+10,a); }
        DoIt& operator=(const DoIt& rhs) { DoIt tmp(rhs); swap(tmp); return *this;}
        void swap(DoIt& rhs) { std::swap(a,rhs.a); }
};

谢谢,sbi,https://stackoverflow.com/users/140719/sbi

c++ stl copy-constructor rule-of-three
3个回答
10
投票

请注意,查尔斯完美地拥有answered your question

无论如何,根据Rule of Three,你的类,有一个析构函数,也应该有一个复制构造函数和赋值运算符。

我是这样做的:

class Doit {
    private:
        char *a;
    public:
        Doit()                   : a(new char[10]) {}
        ~Doit()                    {delete[] a;}
        DoIt(const DoIt& rhs)    : a(new char[10]) {std::copy(rhs.a,rhs.a+10,a);}
        void swap(DoIt& rhs)       {std::swap(a,rhs.a);}
        DoIt& operator=(DoIt rhs)  {swap(rhs); return *this;}
};

6
投票

您使用的所有类型必须是CopyConstructibleAssignable

CopyConstructibleT类型意味着如果tTconst T那么表达T(t)必须产生与原始T相当的t; t。~T()必须有效(可访问的析构函数);和&t必须将t的地址作为[const] T*

Assignable意味着对于TtTu,表达式t = u必须使t等同于u并且类型为T&

请注意,所有这些要求都通过简单的内置类型和POD结构来满足。如果在析构函数或构造函数中执行任何非平凡的操作,则必须确保复制构造函数和复制赋值运算符保留等价语义。


0
投票

所有vector都要求对象是“可赋值的”,这意味着它需要一个copy-constructor,析构函数和赋值运算符,如果你自己不提供它们,它们都是默认生成的。

正如sbi所说,如果你需要其中一种功能,那么你可能需要它们。在您的情况下,您还需要提供复制构造函数和赋值运算符以避免堆损坏。

© www.soinside.com 2019 - 2024. All rights reserved.