c++ - 构造函数不能采用非常量引用

标签 c++ gcc boost c++98

我有以下类(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/

相关文章:

c++ - 如何使用宏作为函数指针?

c++ - 尝试 "blur"C++ 中的矩阵;有缺陷的算法或代码?

c++ - 是否有可能获得 boost 区域设置边界分析以在撇号上进行拆分?

c++ - 在嵌入式环境中替代 boost::shared_ptr

c++ - O(klogn) 时间算法从 Fenwick-Tree 中找到第 k 个最小元素

android - 使用 ndk 在 Android 上将耗时报告为 0ns

c - 为什么代码退出 Ant 不完成

python - 安装 Ta-lib 会产生 gcc 错误

用于 win32/Unix 的 C++ 可移植 NaN

c++ - 我可以在 Boost 中使用 std::function (C++11 lambda) 吗?