繁体   English   中英

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

[英]Constructor can't take non const reference

我有以下课程:

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

typedef boost::shared_ptr<Foo> FooPtr;

我尝试使用这样的:

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

我在VS20012中编译得很好,但它不会在gcc 4.3.4中编译。

这是编译器错误:

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&)

如果我改变Foo的构造以获取const,那么它编译得很好。 但是,我需要通过引用传递。 您认为这个问题是什么?

如此处所述 ,没有C ++ 11支持, make_shared只能通过const引用获取其参数。

在C ++ 11支持下,它可以采用任何引用类型,并将它们转发给构造函数。 据推测这就是VS正在做的事情。

如文档中所述,您可以通过将其包装在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