Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
226 views
in Technique[技术] by (71.8m points)

c++ - boost make_shared takes in a const reference. Any way to get around this?

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 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: error: no matching function for call to `Object::Object(const int&)' note: candidates are: Object::Object(const Object&) note: Object::Object(int&)

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

question from:https://stackoverflow.com/questions/1373896/boost-make-shared-takes-in-a-const-reference-any-way-to-get-around-this

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...