使用unique_ptr的C ++数组char

时间:2015-06-30 09:59:47

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

首先,我知道这不是最好的方法,我只是看看应该怎么做。我创建了一个名为bord的类,它拥有一个成员

SELECT *, x+y as z ORDER BY z

哪个应该是正确的语法,然后我尝试在构造函数中初始化它:

        std::unique_ptr<std::unique_ptr<char>[] > char_bord;

这会导致以下错误堆,我无法解密。

bord::bord():char_bord(new std::unique_ptr<char>[10])
{
    //char_bord=new std::unique_ptr<char>[10]; //This did not seem to work aswell.
    for(int i=0;i<10;i++)
      char_bord[i]=new std::unique_ptr<char>[](new char[10]); 
    return;
}

假设我做错了什么,我做错了什么。

2 个答案:

答案 0 :(得分:5)

以下是一些代码,用于演示我认为您想要的内容:

#include <iostream>
#include <algorithm>
#include <iterator>
#include <memory>

using namespace std;

using array_ptr_type = std::unique_ptr<char[]>;
using array_of_arrays_type = std::unique_ptr<array_ptr_type[]>;

auto main() -> int
{
    auto x = array_ptr_type(new char[10]);
    auto y = array_ptr_type(new char[10]);
    for (int i = 0 ; i < 10 ; ++i)
    {
        x[i] = char('0' + i);
        y[i] = char('0' + 9 - i);
    }

    auto pxy = array_of_arrays_type(new array_ptr_type[2]);
    pxy[0] = move(x);
    pxy[1] = move(y);

    for (int i = 0 ; i < 2 ; ++i) {
        copy(&pxy[i][0], &pxy[i][10], ostream_iterator<char>(cout, ", "));
        cout << endl;
    }
    return 0;
}

预期产出:

0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 
9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 

当然,如你所知,这一切都不推荐 - vector<vector<char>>会更清洁,更易于维护。

答案 1 :(得分:2)

你必须使用专业化:

std::unique_ptr<char[]> chars(new char[1024]);

这是因为std::unique_ptr不支持std::shared_ptr的自定义删除(以这种写作方式)。

std::unique_ptr使用std::default_delete作为删除者。很简单,如果您将参数类型指定为class T,它将使用默认delete,但如果您编写class T[](在此专业化中)std::unique_ptr将使用delete[]。< / p>

但最好使用一些容器而不是c风格的数组。