Question

I'm learning using key_value flyweights and I wrote the following code:

#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");
}
}

When I run it I got the follwing output:

created bar
Copied
Destroyed bar
Destroyed bar

I'd like to avoid the extra copy, since my real Foo is quite expensive to copy. This is also the primary reason I'm using a flyweight. So, is there a way to avoid the extra-copy?

Was it helpful?

Solution

You shouldn't worry about that as compiler may optimize this, in some cases, using RVO. Use compiler options to enable such optimization wherever possible.

And especially with C++11, you should almost never worry about it, as it has introduced move-semantics which do not cost you much even if some temporary objects get created on the fly in flyweight pattern.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top