我正在学习使用 key_value flyweights,我编写了以下代码:
#include <iostream>
#include <string>
#include <boost/flyweight.hpp>
#include <boost/flyweight/key_value.hpp>
#include <boost/flyweight/no_locking.hpp>
class Foo
{
std::string name_;
public:
Foo(const std::string& name) { name_ = name; std::cout << "created " << name << "\n"; }
Foo(const Foo& f) { name_ = f.name_; std::cout << "Copied\n"; }
~Foo() {std::cout << "Destroyed " << name_ << "\n"; }
};
typedef boost::flyweight< boost::flyweights::key_value<std::string, Foo >, boost::flyweights::no_locking > FooLoader;
int main()
{
{
Foo myF = FooLoader("bar");
}
}
当我运行它时,我得到了以下输出:
created bar
Copied
Destroyed bar
Destroyed bar
我想避免额外的副本,因为我真正的 Foo 复制起来非常昂贵。这也是我使用轻量级的主要原因。那么,有没有办法避免多余的副本?