【问题标题】:boost::flyweight doesn't work for classboost::flyweight 不适用于课堂
【发布时间】:2015-04-02 03:08:19
【问题描述】:

首先我将享元用于字符串,它工作正常,但是当我将享元用于结构时。它不起作用。 字符串的第一个测试用例是:

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 中的一些属性我使用了享元。 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 中使用享元,它对使用的内存都没有任何变化。

【问题讨论】:

  • 你甚至没有显示struct A。我们不是通灵者

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


【解决方案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,它的内存使用看起来还不错:

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-31
  • 2019-01-29
  • 1970-01-01
  • 2019-10-28
  • 1970-01-01
相关资源
最近更新 更多