Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constructor can't take non const reference

Tags:

c++

gcc

boost

c++98

I have the following class:

class Foo
{
public:
    explicit Foo(std::vector<std::string>& functionCalls)
    {
    }
};

typedef boost::shared_ptr<Foo> FooPtr;

Which I try to use like this:

std::vector<std::string> functionCalls;
FooPtr foo = boost::make_shared<Foo>(functionCalls);

I compiles fine in VS20012 but it wont compile in gcc 4.3.4.

Here's the compiler error:

boost/boost_1_54_0/boost/smart_ptr/make_shared_object.hpp: In function 'typename boost::detail::sp_if_not_array<T>::type boost::make_shared(const A1&) [with T = Foo, A1 = std::vector<std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::allocator<std::basic_string<char, std::char_traits<char>, std::allocator<char> > > >]':
main.cc:39:   instantiated from here
boost/boost_1_54_0/boost/smart_ptr/make_shared_object.hpp:711: error: no matching function for call to 'Foo::Foo(const std::vector<std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::allocator<std::basic_string<char, std::char_traits<char>, std::allocator<char> > > >&)'
Foo.h:23: note: candidates are: Foo::Foo(std::vector<std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::allocator<std::basic_string<char, std::char_traits<char>, std::allocator<char> > > >&)
Foo.h:21: note:                 Foo::Foo(const Foo&)

If I change the construct of Foo to take a const then it compiles fine. However, I need to pass by reference. What do you think this issue is?

like image 347
Baz Avatar asked Mar 22 '23 22:03

Baz


1 Answers

As documented here, without C++11 support make_shared can only take its arguments by const reference.

With C++11 support, it can take any reference types, and forward them to the constructor. Presumably that's what VS is doing.

As mentioned in the documentation, you can pass a non-const reference by wrapping it in boost::ref:

FooPtr foo = boost::make_shared<Foo>(boost::ref(functionCalls));
like image 96
Mike Seymour Avatar answered Mar 31 '23 23:03

Mike Seymour