C++/ 我有一个关于“新”的问题; “unique_ptr”方法
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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
首先,由于您的动态
char []
数据正在用new []
分配,因此您需要声明buff _
为simory_ptr&lt; char []&gt;
而不是delete []
而不是delete> delete
在释放内存时。分配
operator =
forstd :: simelo_ptr
在您的代码中失败,因为它不接受原始指针,只有另一个std :: simolor_ptr
object ,或nullptr
。试试其中之一:
对于
strcpy()
,您可以使用std :: simelod_ptr
like this:First off, since your dynamic
char[]
data is being allocated withnew[]
, you need to declarebuff_
asunique_ptr<char[]>
instead, so that it will usedelete[]
and notdelete
when freeing the memory.The assignment
operator=
forstd::unique_ptr
fails in your code because it does not accept a raw pointer, only anotherstd::unique_ptr
object, ornullptr
.Try one of these instead:
As for
strcpy()
, you can call it withstd::unique_ptr
like this: