Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
237 views
in Technique[技术] by (71.8m points)

c++ - How to return/copy values of an unique_ptr<unsigned char[]>?

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;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

  1. Return a reference to unique_ptr itself:

    const std::unique_ptr<unsigned char[]>& getBuffValue() const
    {
        return _buff;
    }
    
  2. 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.

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...