boost :: flyweight不适合上课

时间:2015-04-02 03:08:19

标签: c++ boost flyweight-pattern boost-flyweight

首先我使用flyweight作为字符串工作正常,但当我使用flyweight作为结构。它没有用。 字符串的第一个测试用例是:

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;
}

然后我定义了一个结构A,A i中的一些属性使用了flyweight。 testcase2如下:

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;
    }

但无论我是否在A中使用了flyweight,它对使用的内存都没有任何变化。

1 个答案:

答案 0 :(得分:1)

首先关闭:

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

这是:Most vexing parse: why doesn't A a(()); work?


我准备了这个测试程序:

<强> 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";
}

使用valgrind --tool=massif

,其内存使用情况看起来不错

enter image description here