题
我正在使用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");
}
}
.
当我运行它时,我得到了follwing输出:
created bar
Copied
Destroyed bar
Destroyed bar
.
我想避免额外的副本,因为我的真实foo要复制昂贵。这也是我正在使用flyweight的主要原因。所以,有没有办法避免额外的副本?
解决方案
您不应该担心,因为编译器可以在某些情况下使用RVO优化这一点。使用编译器选项以尽可能实现此类优化。
尤其是与c ++ 11,你几乎应该担心它,因为它引入了移动语义,即使在飞行模式的飞行中创建了一些临时对象,也不会花费你的移动语义。
不隶属于 StackOverflow