【发布时间】:2016-12-03 10:03:45
【问题描述】:
我需要创建一个这样的类。但是当我运行这段代码时,我得到:
"Error in `./a.out': free(): invalid next size (fast)"
MyClass 有什么问题?如何正确使用 shared_ptr 作为类成员?
#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;
}
谢谢,我误解了 make_shared 的作用。如果我想使用 int*(不是 std::vector 或 std::array),我应该写这个吗? (并且不要修复其他方法)
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);. -
另请注意,您的问题与智能指针作为数据成员无关。
-
您说您“需要创建这样的类”并且您不“想使用”简单的标准解决方案 (
std::vector)。为什么?你绝对必须使用std::shared_ptr的原因是什么? -
@AnatoliySultanov:你考虑过
std::shared_ptr<std::vector<int>>吗? -
@AnatoliySultanov:是的,你是否需要一个“动态数组”(即真实代码中的
std::vector,除非你有一个非常需要手动的特殊用例如果仅在运行时知道大小,则使用placement new)。只有在程序运行之前知道大小时,才能使用std::array。永远不要使用new[]。
标签: c++ c++11 memory-management smart-pointers