我有以下类(class):
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,那么它可以正常编译。但是,我需要通过引用传递。你认为这个问题是什么?
最佳答案
记录在案here , 如果没有 C++11 的支持,make_shared
只能通过 const
引用获取它的参数。
有了 C++11 的支持,它可以采用任何引用类型,并将它们转发给构造函数。大概这就是 VS 正在做的事情。
如文档中所述,您可以通过将非常量引用包装在 boost::ref
中来传递它:
FooPtr foo = boost::make_shared<Foo>(boost::ref(functionCalls));
关于c++ - 构造函数不能采用非常量引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19537343/