【问题标题】:undefined reference while vector of boost::scoped_ptrboost::scoped_ptr 的向量时未定义的引用
【发布时间】:2013-06-16 11:42:44
【问题描述】:

英特尔编译器 icpc 13.0.1版(gcc 4.4.6版兼容)

#include "boost/scoped_ptr.hpp"
#include <vector>

int main()
{
    std::vector<boost::scoped_ptr<int> > v;
    v.push_back(boost::scoped_ptr<int> (new int(127)));

    return 0;
}

icpc bbb21.cpp

/devjuser1/jp/ccjp/avinokur/tmp/icpclHkUcJ.o: In function `main':
bbb21.cpp:(.text+0xfa): undefined reference to `boost::scoped_ptr<int>::scoped_ptr(boost::scoped_ptr<int> const&)'
bbb21.cpp:(.text+0x136): undefined reference to `boost::scoped_ptr<int>::scoped_ptr(boost::scoped_ptr<int> const&)'
bbb21.cpp:(.text+0x195): undefined reference to `boost::scoped_ptr<int>::scoped_ptr(boost::scoped_ptr<int> const&)'
bbb21.cpp:(.text+0x254): undefined reference to `boost::scoped_ptr<int>::scoped_ptr(boost::scoped_ptr<int> const&)'

怎么了?

【问题讨论】:

    标签: c++ boost vector


    【解决方案1】:

    std::vector::push_back() 使用的类型必须是任一

    • 移动惰性 (void std::vector&lt;T&gt;::push_back( T&amp;&amp; value );) 或
    • 可插入复制 (void std::vector&lt;T&gt;::push_back( const T&amp; value );)。

    cppreference.com, std::vector::push_back()

    Boost docs (1.53), scoped_ptr 建议 scoped_ptr 可以从指针构造,但不能复制或移动构造。

    说明

    scoped_ptr 不能在 C++ 标准库容器中使用。如果您需要一个智能指针,请使用shared_ptr

    (不幸的是,这使您的问题“不是一个真正的问题”或“过于本地化”。;-))

    【讨论】:

      【解决方案2】:

      boost::scoped_ptr 不可复制,而 STL 容器需要可复制构造的元素。

      我的建议是使用以下声明:

      std::vector<int> v;
      

      或者你可以使用 boost::shared_ptr 代替:

      std::vector<boost::shared_ptr<int> > v;
      

      【讨论】:

      • @Alex 没问题,很高兴它有帮助。
      • @Alex,请不要在 cmets 中写下您的感谢,而是使用接受按钮。
      【解决方案3】:

      您不能复制 scoped_ptr,正如错误所说,scoped_ptr 的复制构造函数不可用。您可以改用shared_ptr,它提供几乎相同的功能,但可以解决您的问题。

      【讨论】:

        【解决方案4】:

        如果您有在 STL 中实现移动语义的现代实现,请使用 std::vector&lt;std::unique_ptr&lt;int&gt; &gt;。这是与 scoped_ptr 最接近的等价物。

        【讨论】:

          猜你喜欢
          • 2015-08-23
          • 1970-01-01
          • 2020-12-14
          • 1970-01-01
          • 2016-05-11
          • 2019-07-05
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多