首先我将享元用于字符串,效果很好,但是当我将享元用于结构时。它不起作用。 字符串的第一个测试用例是:
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?
我准备了这个测试程序:
#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
它的内存使用情况看起来不错:
关于c++ - boost::flyweight 不适用于类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29404369/