2016-10-03 94 views
0

所以我用从一个自定义的矢量容器:https://github.com/patr0nus/Vector/blob/master/Vector.h自定义矢量不支持的unique_ptr

,我试图创造的unique_ptr指针的向量自定义类对象。

它曾经失败:

error: object of type 'std::__1::unique_ptr std::__1::default_delete>' cannot be assigned because its copy assignment operator is implicitly deleted

我固定它通过添加以下代码vector.h:

void push_back(T&& val) 
    { 
     resize(m_size + 1); 
     m_container[m_size - 1] = std::move(val); 
    } 

现在的问题是,我无法遍历这个矢量和其他功能,如swap是失败:

no matching function for call to 'swap' 
     swap(*__x4, *__x5); 
candidate template ignored: could not match 'tuple' against 'unique_ptr' 
swap(tuple<_Tp...>& __t, tuple<_Tp...>& __u) 

我需要如何解决日一些指导这些问题。

+0

这个载体似乎是专为使用只有POD类型。 –

+9

使用'std :: vector'是解决方案。为什么你首先需要这个定制的?这个实现的问题是绝对需要'T'是CopyConstructible,当'std :: unique_ptr'不是。 – AndyG

+3

嗯......为什么不使用std :: vector? – mascoj

回答

5

您不能使用patr0nus/Vector与非POD类型。原因很简单:它在很多地方使用memcpy,并且要求类型被复制为构造函数。

与其他不是POD的东西一起使用实际上是未定义的行为。不要将该向量用于非POD类型。没有办法绕过它。您可能已经知道,您可以使用定义明确的实现,该实现尊重一组精确的需求,并且可能比该矢量实现更优化:std::vector

如果您有一些内存或分配约束,您可以实现自定义分配器。

1

要添加到给定的答案中,因为您的矢量类仅适用于POD类型,所以确保您只使用POD类型的方式是使用std::is_pod函数以及static_assert。使用这些C++工具将禁止创建违反​​POD要求的程序。

当你构建的载体,可以使测试这些功能:

#include <algorithm> 
//... 
template<typename T> 
class Vector 
{ 
    Vector(int initialSize = 1) 
    { 
     static_assert(std::is_pod<T>(), "Sorry, only POD types are allowed"); 
    //... 
    } 

    Vector(const Vector &source) 
    { 
     static_assert(std::is_pod<T>(), "Sorry, only POD types are allowed"); 
     //... 
    } 
    //... 
}; 

这确保了如果有人是做这样的事情:

Vector<std::string> sV; 

编译器错误将显示而不是代码编译,并导致你现在看到的问题。

+0

'is_pod'可以转换为bool,所以'static_assert(std :: is_pod {},“blah”)'是合适的。另外,你可以在课堂顶端声明一次。 :) – GManNickG

0

在调整大小()函数,你必须:

{ 
... 
      m_capacity = size * 2;//The new capacity is double of the size. 
      T* oldPtr = m_container; 
      m_container = (T*)malloc(m_capacity * sizeof(T));//Allocate the new container. 
      memcpy(m_container, oldPtr, m_size * sizeof(T));//Copy the elements. 
      destory(oldPtr, m_size);//Destory the old container. 
      free(oldPtr); 
... 
} 

所以你需要把POD(普通旧数据)元素你向量:
What are POD types in C++?