c++ - unique_ptr<char[]> 困惑

标签 c++ unique-ptr

我有一个类,我希望其中的一个函数将唯一的 ptr 对象传递给 char 数组。但是我对独特指针的几个特征感到困惑。我知道当不再有对该对象的引用时会自动调用析构函数,但对于原始变量仍然相同吗?比如我这样做,内存会不会被删除?

class A {
private:
public:
    A(std::unique_ptr<char[]> data) {
        data = nullptr;
    }
    ~A();

};
int main() {
    auto data = std::make_unique<char[]>(10);
    A a(std::move(data));
    return 0;
 }

我的下一个问题是:如果我有一个要指向数据的私有(private)对象,为什么这会导致编译器错误?

class A {
private:
    std::unique_ptr<char[]> internaldata;
public:
    A(std::unique_ptr<char[]> data) {
        internaldata = data;
    }
    ~A() {
        internaldata = nullptr;
    }

};
int main() {
    auto data = std::make_unique<char[]>(10);
    A a(std::move(data));
    return 0;
 }

然而,当我在分配它时调用 std::move 时,代码编译正常。

class A {
private:
    std::unique_ptr<char[]> internaldata;
public:
    A(std::unique_ptr<char[]> data) {
        internaldata = std::move(data);
    }
    ~A() {
        internaldata = nullptr;
    }

};
int main() {
    auto data = std::make_unique<char[]>(10);
    A a(std::move(data));
    return 0;
 }

但为什么我必须在这里调用 std::move 两次?一次用于传递参数然后第二次用于分配?在此过程中,引用计数究竟发生了什么,是否发生了重新分配、复制和删除?

最后,在减速过程中是否可以向智能指针传递数据?因为目前我是这样做的:

    auto data = std::make_unique<char[]>(10);
    char* buf = data.get();
    strcpy(buf, "hello\0");

但是是否可以按照以下方式做一些事情:

    char hellobuffer[] = "hello";
    auto data = std::make_unique<char[]>(hellobuffer);

在何处自动为数据分配存储 hellobuffer 所需的正确大小并复制数据本身?

最佳答案

I'm aware a destructor is called automatically when there are no more references to the object but is still the same for primitive variables?

析构函数总是在逻辑上被调用。但是,由于像 int 这样的事情和 char是微不足道的可破坏的,编译器明白实际上不应该调用任何东西。

For instance if I do this, will the memory be deleted?

是的——std::unique_ptr<T> 的全部要点|是你的内存会被自动处理。

A(std::unique_ptr<char[]> data) {
    internaldata = data;
}

该示例无法编译,因为 internaldata = data正在调用复制赋值运算符并复制 std::unique_ptr实例是不允许的(因此是唯一位)。

And what exactly occurs in terms of reference count during that process, does a reallocation, copy and deletion occur?

没有引用计数 -- std::unique_ptr要么是指某物,要么是空的。当你std::move来自std::unique_ptr ,移出的变量变为空。如果您正在寻找引用计数指针类型,请参阅 std::shared_ptr<T> .

And finally, is it possible to pass data into the smart pointer during the deceleration?

没有。对于 std::make_unique<T[]> , 你只能传递 std::size_t (参见 overload 2)。为您正在寻找的内容编写包装函数应该很容易。

关于c++ - unique_ptr<char[]> 困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58758887/

相关文章:

c++ - 无法将空函数指针作为模板参数传递

c++ - 如何将 vector 插入到特定位置的另一个 vector 中,这样我将同时获得这两个 vector 的大 vector ,并且该位置将被覆盖?

c++ - 有效地从 unordered_set 中删除 unique_ptr

c++ - 为什么这个 RAII 只 move 类型不能正确模拟 `std::unique_ptr` ?

c++ - 将 for_each 与 std::unique_ptr 一起使用

c++ - Qt中除了单选按钮之外是否有类似gui元素的开关

c++ - 以 clang 格式对齐函数声明

c++ - 使用 pthread 唤醒多线程的最佳方法

c++ - 在 C++ 中发布二维数组的打印元素

c++ - static unique_ptr 两次调用析构函数