如何返回/复制unique_ptr<unsigned char[]>的值? [英] How to return/copy values of an unique_ptr&lt;unsigned char[]&gt;?

查看:32
本文介绍了如何返回/复制unique_ptr<unsigned char[]>的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的类,在 C++ 中有一个属性 std::unique_ptr.我想要一个将字符串转换为 std::unique_ptr 的函数,另一个将 float 转换为 std::unique_ptrcode>,第三个返回属性 std::unique_ptr.我的头文件正在编译,但源 CPP 没有编译.甚至返回属性也没有编译.

I have a simple class with one attribute std::unique_ptr<unsigned char[]> in C++. I want to have a function that converts string to std::unique_ptr<unsigned char[]>, other to convert float to std::unique_ptr<unsigned char[]>, and a third to return the attribute std::unique_ptr<unsigned char[]>. My header is compiling but the source CPP is not. Even the return attribute is not compiling.

#include <memory>
class SkinnyBuffer {
private:
    std::unique_ptr<unsigned char[]> _buff;
public:
    ~SkinnyBuffer();
    SkinnyBuffer();
    void setBuffValue(float f);
    void setBuffValue(std::string str);
    std::unique_ptr<unsigned char[]>* getBuffValue();
};

#include "utils/SkinnyBuffer.h"
SkinnyBuffer::~SkinnyBuffer() { }
SkinnyBuffer::SkinnyBuffer() { }
void SkinnyBuffer::setBuffValue(float f) {
    // How to implement it
    _buff = f;
}
void SkinnyBuffer::setBuffValue(std::string str) {
    _buff = std::unique_ptr<unsigned char[]>(str.data(), str.data() + str.length());
}
std::unique_ptr<unsigned char[]>* SkinnyBuffer::getBuffValue() {
    return &_buff;
}

推荐答案

std::unique_ptr 是一个不可复制的对象.如果您需要只读访问权限,您有两个(主要)选项:

std::unique_ptr is a non-copyable object. If you need a read-only access to it, you have two (main) options:

  1. 返回对 unique_ptr 本身的引用:

const std::unique_ptr<unsigned char[]>& getBuffValue() const
{
    return _buff;
}

  • 返回指向托管数组的常量指针:

  • Return a const pointer to the managed array:

    const unsigned char* getBuffValue() const
    {
        return _buff.get();
    }
    

  • 要将字符串分配给缓冲区,您可以:

    To assign a string to the buffer, you can do:

    void setBuffValue(const std::string& str)
    {
        _buff = std::make_unique<unsigned char []>(str.length() + 1);
        std::copy_n(str.c_str(), str.length() + 1, _buff.get());
    }
    

    请注意,您必须将终止空字符复制到缓冲区.否则对于外界来说几乎是无用的,因为用户不会知道它的长度.

    Note that you have to copy the terminating null character to your buffer. Otherwise it will be almost useless for the outside world because its length will not be known to the user.

    但是你真的需要 std::unique_ptr 吗?std::vector 在这里似乎更合适.

    But do you really need std::unique_ptr<unsigned char[]>? std::vector seems to be more appropriate here.

    这篇关于如何返回/复制unique_ptr<unsigned char[]>的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆