c++ - boost::flyweight 不适用于类

标签 c++ boost flyweight-pattern boost-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中的一些属性我使用了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,它对使用的内存没有任何改变。

最佳答案

首先:

    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

关于c++ - boost::flyweight 不适用于类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29404369/

相关文章:

c++ - 红黑树插入代码显示段错误 11

c++ - 两次调用io_service::run方法有什么影响

c++/boost fusion句柄父类

c++ - 如何将卡方分布与 C++ Boost 库一起使用?

Java 实习生池实现创建了太多临时对象

c++ - 为 C++ 配置 Vim

c++ - ISO C++ 说这些是模棱两可的,即使第一个最差的转换比第二个最差的转换要好

c++ - 将库函数模板化以避免编译器指令是否有益?

java - Java 的 String Intern 是享元吗?

c++ - 我们可以使用子字符串的 const ref 吗?