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

前端之家收集整理的这篇文章主要介绍了c – 在STL向量中存储对象 – 最小的方法集前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
什么是复杂对象的“最小框架”(必要的方法)(具有显式的malloced内部数据),我想将其存储在STL容器中,例如<载体GT ;?

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

  1. #include <vector>
  2. #include <cstring>
  3. using namespace std;
  4. class Doit {
  5. private:
  6. char *a;
  7. public:
  8. Doit(){a=(char*)malloc(10);}
  9. ~Doit(){free(a);}
  10. };
  11.  
  12. int main(){
  13. vector<Doit> v(10);
  14. }

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

在valgrind:

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

更新:

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

  1. class DoIt{
  2. private:
  3. char *a;
  4. public:
  5. DoIt() { a=new char[10]; }
  6. ~DoIt() { delete[] a; }
  7. DoIt(const DoIt& rhs) { a=new char[10]; std::copy(rhs.a,rhs.a+10,a); }
  8. DoIt& operator=(const DoIt& rhs) { DoIt tmp(rhs); swap(tmp); return *this;}
  9. void swap(DoIt& rhs) { std::swap(a,rhs.a); }
  10. };

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

解决方法

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

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

我是这样做的:

  1. class Doit {
  2. private:
  3. char *a;
  4. public:
  5. Doit() : a(new char[10]) {}
  6. ~Doit() {delete[] a;}
  7. DoIt(const DoIt& rhs) : a(new char[10]) {std::copy(rhs.a,a);}
  8. void swap(DoIt& rhs) {std::swap(a,rhs.a);}
  9. DoIt& operator=(DoIt rhs) {swap(rhs); return *this;}
  10. };

猜你在找的C&C++相关文章