【问题标题】:How to pass the reference of unique_ptr.get() to a function如何将 unique_ptr.get() 的引用传递给函数
【发布时间】:2019-09-20 18:52:02
【问题描述】:

我有以下代码,但它报告error: invalid initialization of non-const reference of type 'char*&' from an rvalue of type 'std::unique_ptr<char []>::pointer {aka char*}'。我想知道我是否可以通过这种方式在函数中为 unique_ptr 缓冲分配。

#include <iostream>
#include <string>
#include <memory>

void buffer_test(char* &buffer){

    buffer = new char[100];
}

int main()
{



    std::unique_ptr<char []> buffer{};

    buffer_test(buffer.get());

    std::cout << buffer[0] << std::endl;

    std::cout << "finish";
}

【问题讨论】:

  • 制作别名指针有什么意义?

标签: c++ reference c++14 unique-ptr


【解决方案1】:

unique_ptr::get 不返回对unique_ptr 对象内的指针对象的引用。它返回指针值。你会得到它的副本,而不是参考。

所以你不能将该值传递给一个对指针进行非常量引用的函数。如果你想填写unique_ptr的实际存储指针值,你将*必须*将unique_ptr本身传递给buffer_test,或者只是让buffer_test返回它分配的指针。

或者更好的是,让它返回一个unique_ptr 到它分配的缓冲区。因为基本上没有理由不这样做。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-10
    • 2011-10-31
    • 2014-08-21
    • 1970-01-01
    • 2019-03-04
    • 1970-01-01
    • 2016-07-17
    • 1970-01-01
    相关资源
    最近更新 更多