C++/ 我有一个关于“新”的问题; “unique_ptr”方法

发布于 2025-01-20 20:48:50 字数 623 浏览 2 评论 0原文

class Manager {
private:
    //char* buff_;
    int buff_size_;
    int* ref_;
    unique_ptr<char> buff_;

public:
    Manager() {
        buff_size_ = 1;
        buff_ = nullptr;
        ref_ = new int;
        *ref_ = 1;
    }
    Manager(const char* s) {
        buff_size_ = strlen(s);
        buff_ = new char[buff_size_ + 1]; //error E0349 no operator = matches these operands
        //strcpy(buff_, s);
        ref_ = new int;
        *ref_ = 1;
    }
}

我想将char*替换为unique_ptr

如何在Manager(const char*s){}中编写new

class Manager {
private:
    //char* buff_;
    int buff_size_;
    int* ref_;
    unique_ptr<char> buff_;

public:
    Manager() {
        buff_size_ = 1;
        buff_ = nullptr;
        ref_ = new int;
        *ref_ = 1;
    }
    Manager(const char* s) {
        buff_size_ = strlen(s);
        buff_ = new char[buff_size_ + 1]; //error E0349 no operator = matches these operands
        //strcpy(buff_, s);
        ref_ = new int;
        *ref_ = 1;
    }
}

I want to replace char* with unique_ptr.

How can I write new in Manager(const char*s){}?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

无名指的心愿 2025-01-27 20:48:50

首先,由于您的动态char []数据正在用new []分配,因此您需要声明buff _simory_ptr&lt; char []&gt;而不是delete []而不是delete> delete在释放内存时。

分配operator = for std :: simelo_ptr在您的代码中失败,因为它不接受原始指针,只有另一个std :: simolor_ptr object ,或nullptr

试试其中之一:

buff_.reset(new char[buff_size_ + 1]);
buff_ = std::unique_ptr<char[]>(new char[buff_size_ + 1]);
// C++14 and later only
buff_ = std::make_unique<char[]>(buff_size_ + 1);

对于strcpy(),您可以使用std :: simelod_ptr like this:

strcpy(buff_.get(), s);

First off, since your dynamic char[] data is being allocated with new[], you need to declare buff_ as unique_ptr<char[]> instead, so that it will use delete[] and not delete when freeing the memory.

The assignment operator= for std::unique_ptr fails in your code because it does not accept a raw pointer, only another std::unique_ptr object, or nullptr.

Try one of these instead:

buff_.reset(new char[buff_size_ + 1]);
buff_ = std::unique_ptr<char[]>(new char[buff_size_ + 1]);
// C++14 and later only
buff_ = std::make_unique<char[]>(buff_size_ + 1);

As for strcpy(), you can call it with std::unique_ptr like this:

strcpy(buff_.get(), s);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文