std :: auto_ptr在我的模板类中编译,但不在std :: unique_ptr中编译

时间:2013-10-01 16:45:13

标签: c++ templates c++11 unique-ptr auto-ptr

我开始了一个模板类,它应该管理固定长度的双端队列。我想添加一个函数,将返回转换为向量的数据。因为我不能确定这将使用良好的NRVO(命名返回值优化)进行编译,并且理论上数据可能非常大,所以我决定将返回包装在unique_ptr中(以避免在结束时大量调用复制构造函数)。奇怪的是,这没有编译:

 In file included from FixedDeque.cpp:8:
 FixedDeque.h:26: error: ISO C++ forbids declaration of 'unique_ptr' with no type
 FixedDeque.h:26: error: invalid use of '::'
 FixedDeque.h:26: error: expected ';' before '<' token
 FixedDeque.cpp:27: error: expected constructor, destructor, or type conversion before '<' token

我在OS X雪豹上使用g ++作为NetBeans中的编译器。

然而,当我更改完全相同的代码以使用auto_ptr时,整个事情就会编译。 unique_ptr和模板有问题吗? fyi,我确实确保连续'&lt;'之间有空格和'&gt;'在这两种情况下(以避免解释管道符号)。

这是我的代码,如果有人可以解释这个问题我真的很感激:

部首:

#include "deque"
#include "vector"
#include "memory"
template<typename T> class FixedDeque {
public:
  FixedDeque(int size);
  FixedDeque(const FixedDeque<T>& orig);
  virtual ~FixedDeque();
  // adding an auto_ptr/unique_ptr because not sure the C++ NRVO is applied in the compiler
  std::unique_ptr< std::vector<T> > getVectorCopy() const;
private:
  std::deque<T> _deq;
  int _maxSize;
};


#include "FixedDeque.h"
template<typename T> FixedDeque<T>::FixedDeque(int size)  : _deq(size), _maxSize(size)
{ }
template<typename T> FixedDeque<T>::FixedDeque(const FixedDeque<T>& orig) : _deq(orig._deq) {}
template<typename T> FixedDeque<T>::~FixedDeque() {}  
template<typename T> std::unique_ptr< std::vector<T> > FixedDeque<T>::getVectorCopy() const
{
    std::vector<T>* apVector = new std::vector<T>();
    return( std::unique_ptr< std::vector<T> >(apVector) );
}  

同样,简单地用auto_ptr替换unique_ptr会使整个事情编译。我知道我的实现返回一个指向空向量的指针。我只想关注使用unique_ptr和auto_ptr可能出错的地方。

谢谢!

1 个答案:

答案 0 :(得分:0)

您的代码大多是正确的,除了您无法编译类模板。要使其工作,您必须在头文件中声明并实现类模板,#include头文件并在程序上实例化类模板。请参阅以下示例:

// This is FixedDeque.hpp
#include <iostream>
#include <deque>
#include <vector>
#include <memory>

template<typename T> class FixedDeque {
public:
  FixedDeque(int size);
  FixedDeque(const FixedDeque<T>& orig);
  virtual ~FixedDeque();
  // adding an auto_ptr/unique_ptr because not sure the C++ NRVO is applied in the compiler
  std::unique_ptr< std::vector<T> > getVectorCopy() const;
private:
  std::deque<T> _deq;
  int _maxSize;
};

template<typename T> FixedDeque<T>::FixedDeque(int size)  : _deq(size), _maxSize(size)
{ }
template<typename T> FixedDeque<T>::FixedDeque(const FixedDeque<T>& orig) : _deq(orig._deq) {}
template<typename T> FixedDeque<T>::~FixedDeque() {}  
template<typename T> std::unique_ptr< std::vector<T> > FixedDeque<T>::getVectorCopy() const
{
    std::vector<T>* apVector = new std::vector<T>();
    return( std::unique_ptr< std::vector<T> >(apVector) );
}  

// This is FixedDeque_Test.cpp
int main() {
    FixedDeque<int> fdeque(10);
    std::unique_ptr<std::vector<int>> vec = fdeque.getVectorCopy();
    std::cout << vec->size() << std::endl;
    return 0;
}
相关问题