简体   繁体   English

构造函数不能采用非const引用

[英]Constructor can't take non const reference

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. 我在VS20012中编译得很好,但它不会在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. 如果我改变Foo的构造以获取const,那么它编译得很好。 However, I need to pass by reference. 但是,我需要通过引用传递。 What do you think this issue is? 您认为这个问题是什么?

As documented here , without C++11 support make_shared can only take its arguments by const reference. 如此处所述 ,没有C ++ 11支持, make_shared只能通过const引用获取其参数。

With C++11 support, it can take any reference types, and forward them to the constructor. 在C ++ 11支持下,它可以采用任何引用类型,并将它们转发给构造函数。 Presumably that's what VS is doing. 据推测这就是VS正在做的事情。

As mentioned in the documentation, you can pass a non-const reference by wrapping it in boost::ref : 如文档中所述,您可以通过将其包装在boost::ref来传递非const引用:

FooPtr foo = boost::make_shared<Foo>(boost::ref(functionCalls));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM