【问题标题】:Constructor can't take non const reference构造函数不能采用非 const 引用
【发布时间】:2013-10-23 09:01:23
【问题描述】:

我有以下课程:

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 ,那么它编译得很好。但是,我需要通过引用传递。你觉得这个问题是什么?

【问题讨论】:

  • @juanchopanza:右值在哪里?
  • @LightnessRacesinOrbit 我显然误读了错误。我删除了我以前令人困惑的 cmets。

标签: c++ gcc boost c++98


【解决方案1】:

如文档中的 here 所述,如果没有 C++11 支持,make_shared 只能通过 const 引用获取其参数。

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

如文档中所述,您可以通过将非常量引用包装在 boost::ref 中来传递它:

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

【讨论】:

    猜你喜欢
    • 2012-06-01
    • 2018-07-13
    • 2017-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-01
    • 2015-05-17
    • 2011-09-19
    相关资源
    最近更新 更多