boost::flyweight doesn't work for class

271 views Asked by At

first i used flyweight for string which works fine, but when i use flyweight for a struct. it doesn't work. the first test case for string is:

static void testflyweightString()
{
char tmp[0];
vector<boost::flyweight<string>> boost_v;
for(int i=0;i<10000000;i++)
{
sprintf(tmp,"zws_%d",i/1000);
boost_v.pushback(boost::flyweight<string>(tmp));
}
return;
}

then i defined a struct A, some properties in A i used flyweight. testcase2 is as below:

static void testflyweightA()
    {
    vector<A> boost_v;
    for(int i=0;i<10000000;i++)
    {
    A a();//here new some A;
    boost_v.pushback(a);
    }
    return;
    }

but it doesn't have any change for memory used whether i used flyweight in A or not.

1

There are 1 answers

1
sehe On

First off:

    A a();//here new some A;

This is: Most vexing parse: why doesn't A a(()); work?


I prepared this test program:

Live On Coliru

#include <boost/flyweight.hpp>
#include <vector>
#include <iostream>

static void testflyweightString() {
    std::cout << __FUNCTION__ << "\n";
    std::vector<boost::flyweight<std::string> > boost_v;
    for (int i = 0; i < 10000000; i++) {
        boost_v.emplace_back("zws_" + std::to_string(i/1000));
    }
}

struct A {
    boost::flyweight<std::string> s;
    A(std::string const& s) : s(s) { }
};

static void testflyweightA() {
    std::cout << __FUNCTION__ << "\n";
    std::vector<A> boost_v;
    for (int i = 0; i < 10000000; i++) {
        boost_v.push_back("zws_" + std::to_string(i/1000));
    }
}

int main() {
    testflyweightString();
    testflyweightA();
    std::cout << "Done\n";
}

Its memory usage looked ok using valgrind --tool=massif:

enter image description here