升压make_shared接受一个const引用。任何方式来解决这个问题? [英] boost make_shared takes in a const reference. Any way to get around this?

查看:238
本文介绍了升压make_shared接受一个const引用。任何方式来解决这个问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用我的计划提振共享指针,我有一个类,它作为一个参数,另一个对象的引用。我遇到的问题是make_shared功能要求所有的参数是一个const引用,我得到的编译错误,如果我的类的构造函数不允许const引用参数的传递。

I am using boost shared pointers in my program, and I have a class that takes as a parameters a reference to another object. The problem I am running into is the make_shared function requires all parameters to be a const reference, and I get compile errors if my class's constructor doesn't allow const reference parameters to be passed in.

有谁知道这背后的原因是什么?此外,有什么我可以做的来解决这个问题?

Does anyone know the reason behind this? Also, is there anything I can do to get around this?

什么是给我的问题code例如:

code example of what is giving me problems:

class Object
{
  public:
    Object(int& i)
    {
      i = 2;
    }
};


int main(int argc, char *argv[])
{
  int i = 0;
  boost::shared_ptr<Object> obj = boost::make_shared<Object>(i);
  return 1;
}

这将导致指出以下编译器错误

This results in a compiler error that states the following

:make_shared.hpp:185:错误:调用`对象:对象(const int的&放大器;)没有匹配的函数
注意:考生:对象:对象(const对象和放大器;)
注意:对象:对象(INT和放大器;)

:make_shared.hpp:185: error: no matching function for call to `Object::Object(const int&)' note: candidates are: Object::Object(const Object&) note: Object::Object(int&)

如果该参数为对象的构造是一个const int的,这个工程。我很好奇,为什么make_shared的行为这种方式。

If the parameter to Objects constructor is a const int, this works. I am curious as to why make_shared behaves this way.

推荐答案

<一个href=\"http://www.boost.org/doc/libs/1%5F39%5F0/libs/smart%5Fptr/make%5Fshared.html\">http://www.boost.org/doc/libs/1_39_0/libs/smart_ptr/make_shared.html说:如果你需要一个非const引用传递给T的构造函数,可以通过包装中的参数调用的boost :: REF这样做。该网页上的其他文字似乎支持吕迪格汉克的答案。

http://www.boost.org/doc/libs/1_39_0/libs/smart_ptr/make_shared.html says: "If you need to pass a non-const reference to a constructor of T, you may do so by wrapping the parameter in a call to boost::ref." Other text on that page seems to support Rüdiger Hanke's answer.

这篇关于升压make_shared接受一个const引用。任何方式来解决这个问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆