I need to create a class like this. But when I run this code, I get:
"Error in `./a.out': free(): invalid next size (fast)"
What's wrong with MyClass? How to use shared_ptr as a class member correctly?
#include <memory>
class MyClass
{
public:
MyClass(unsigned size) {
_size = size;
_arr = std::make_shared<int>(size);
for (int i = 0; i < size; i++)
_arr.get()[i] = 0;
}
MyClass(const MyClass& other) {
_arr = other._arr;
_size = other._size;
}
MyClass& operator=(const MyClass& other) {
_arr = other._arr;
_size = other._size;
}
void setArr(std::shared_ptr<int> arr, unsigned size) {
_size = size;
_arr = arr;
}
~MyClass() {
_arr.reset();
}
private:
std::shared_ptr<int> _arr;
unsigned _size;
};
int main() {
MyClass m(4);
return 0;
}
Thank you, I misunderstood what make_shared makes. If I want to use int* (not std::vector or std::array), should I write this? (and don't fix the other methods)
MyClass(unsigned size) {
_size = size;
_arr = std::shared_ptr<int>(new int[size]);
for (int i = 0; i < size; i++)
_arr.get()[i] = 0;
}
std::make_shared<int>(size);
. – juanchopanzastd::vector
). Why? What is the reason that you absolutely must usestd::shared_ptr
? – Christian Hacklstd::shared_ptr<std::vector<int>>
? – Christian Hacklstd::vector
in real code, unless you have a very special use case that demands manual use of placement new) if the size is only known at run-time.You can usestd::array
only if you know the size before the program runs. Just don't usenew[]
, ever. – Christian Hackl