c++ - 创建相似对象时减少内存浪费

标签 c++ class

假设我有一个对象,我想为它制作许多拷贝,这些拷贝大部分相同,但略有不同。在不过度复制的情况下共享这些对象之间的公共(public)属性的正确方法是什么?

举个具体的例子

class A:
{
   BigData bd;
   LittleData ld;       

   A(const BigData& bd, LittleData ld): bd {bd}, ld {ld} {}
};

我从一个初始对象 A 开始,用不同的小数据但相同的大数据制作 A 的多个拷贝。我本来想对大数据使用 static 关键字,但我不能,因为大数据依赖于初始化。

最佳答案

您可以使用 shared_ptr 实现简单的写时复制。 IE。将智能指针存储在 A 类对象之间共享的大数据上。当您需要为 A 的特定对象修改此大数据时 - 用修改后的深拷贝(克隆对象)替换智能指针:

即像这样的东西:

#include <functional>
#include <utility>

class A {
public:
   typedef std::shared_ptr<BigData> cow_t;
   A(cow_t&& bd, const LittleData& ld):
      bd_( std::forward<cow_t>(bd) ),
      ld_(ld)
   {}
  // rule of 5 
   A(const A& c):
     bd_(c.bd_),
     ld_(c.ld_) 
   {}
   A& opertor=(const A& rhs) {
      A( rhs ).swap( *this );
      return *this;
   } 
   A(A&& c) noexcept:
     bd_( std::move(c.bd_) ),
     ld_( std::move(c.ld_) ) 
   {}
   A& operator=(A&& rhs) noexcept {
     A( std::forward<A>(rhs) ).swap( *this );
     return *this;
   }
   ~A() noexcept = default;
   void swap(A& other) {
      bd_.swap( other.bd_ );
      std::swap(ld_,other.ld_);
   } 
   // Deep copy big data when you need to modify it
   void updateBig(std::function<cow_t(cow_t&&)>  handler)  {
      return bd_ = handler( std::move(bd_) );
   }
   // Shallow copy (get the constant pointer) on big data when you simply need to read it  
   const BigData* big() const {
       return bd_.get();
   }  
   // Always deep copy for LittleData
   LittleData little() const {
      return ld_;
   }
private:
   cow_t bd_;
   LittleData ld_;
}

...
A a( std::make_shared(big), little );
a.updateBig([] (std::shared_ptr<BigData>&& data) {
  // Some deep copy (clone) before update, by copy constructor for example
  shared_ptr<BigData> update = std::make_shared( *data );
  // some modification
  update->modify();
  return update;
});

关于c++ - 创建相似对象时减少内存浪费,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57249654/

相关文章:

c++ - 连接和压缩 std::vector<std::string> 的最佳方法

c++ - 没有成员可用于声明为类变量的对象

c++ - C++ 中的继承 : Error C2011

c++ - 类中的 ifstream 变量

ios - 重用类最佳实践

c++ - 如何在主函数中连接到数据库,然后从其他函数中引用它

C++,类作为方法的参数,而不是模板

java - 使用 Class 和/或 ClassLoader 实例化 Java 类

html - 当前浏览器对.class Name.和ClassName的支持是什么?

c++ - 崩溃生成转储