gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 02:14:44 26 4
gpt4 key购买 nike

假设我有一个对象,我想为它制作许多拷贝,这些拷贝大部分相同,但略有不同。在不过度复制的情况下共享这些对象之间的公共(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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com