Reputation: 1
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){}
?
Upvotes: 0
Views: 97
Reputation: 596256
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);
Upvotes: 3