如何防止复制蝇量级对象

How can I prevent copying of flyweight objects?

本文关键字:对象 何防止 复制      更新时间:2023-10-16

我正在使用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 << "Copiedn"; }
    ~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复印起来很贵。这也是我使用蝇量级的主要原因。那么,有没有办法避免额外的副本?

您不必担心,因为编译器可能会在某些情况下使用RVO对此进行优化。尽可能使用编译器选项启用此类优化。

尤其是对于C++11,您几乎不应该担心它,因为它引入了移动语义,即使在轻量级模式中动态创建了一些临时对象,也不会花费太多成本。