用共享指针向量提升lambda

时间:2011-10-07 11:21:05

标签: c++ boost boost-lambda

下面是一个稍微修改过的代码,它来自一个很好的例子,如何将一个字符串向量的值复制到另一个对象向量。 (见:another copy algorithm

#include <algorithm>
#include <cstdlib>
#include <iostream>
#include <string>
#include <vector>
#include <boost/lambda/bind.hpp>
#include <boost/lambda/lambda.hpp>

#include <boost/shared_ptr.hpp>
#include <boost/make_shared.hpp>

using boost::shared_ptr;
using boost::make_shared;
using namespace boost::lambda;

class Object
{
public:
    std::string Name;

    Object(const std::string& Name_ = "")
        : Name(Name_)
    {
    }
};

int main()
{
    //std::vector<Object> objects(3, Object());
    std::vector<shared_ptr<Object> > objects(3, make_shared<Object>());

    std::vector<std::string> names;
    names.push_back("Alpha");
    names.push_back("Beta");
    names.push_back("Gamma");
    std::vector<std::string>::const_iterator names_it;
    names_it = static_cast<const std::vector<std::string>&>(names).begin();

    //std::for_each(objects.begin(), objects.end(), bind(&Object::Name, _1) = *var(names_it)++);
    std::for_each(objects.begin(), objects.end(), bind(&Object::Name, *_1) = *var(names_it)++);

    //std::vector<Object>::iterator it, end = objects.end();
    std::vector<shared_ptr<Object> >::iterator it, end = objects.end();
    for (it = objects.begin(); it != end; ++it) {
        //std::cout << it->Name << std::endl;
        std::cout << (*it)->Name << std::endl;
    }

    return EXIT_SUCCESS;
}

在这种情况下,我使用动态分配的对象,并且由于boost :: lambda :: bind无法处理boost :: bind这样的更改,我需要取消引用占位符才能编译:

std::for_each(objects.begin(), objects.end(), bind(&Object::Name, *_1) = *var(names_it)++);

然后在输出中我得到了:

Gamma
Gamma
Gamma

你的解释是什么?

1 个答案:

答案 0 :(得分:3)

std::vector<shared_ptr<Object> > objects(3, make_shared<Object>());

这相当于:

shared_ptr<Object> object = make_shared<Object>();
std::vector<shared_ptr<Object> > objects(3, object);

然后,向量构造函数将生成该object指针的3个副本,这些指针将全部引用同一个 unique Object(就是说,*object)。使用单独的指针填充向量,每个指针都使用自己的Object初始化。