如何使用std::shared_ptr成为class会员?

How to use std::shared_ptr as class member?

我需要像这样创建一个 class。但是当我 运行 这段代码时,我得到:

"Error in `./a.out': free(): invalid next size (fast)"

MyClass 有什么问题?如何正确使用shared_ptr作为class会员?

#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 是如何工作的。

基本上,std::make_shared

Constructs an object of type T and wraps it in a std::shared_ptr

在你的例子中 Tint,所以 std::make_shared 创建了一个 int 类型的对象并将其包装在 std::shared_ptr 中。结果,内存分配给单个 int,而不是分配给 int 的数组,您的程序会导致 Undefined Behaviour.

我想你可以使用 std::default_delete 来避免问题:

_arr = std::shared_ptr<int>(new int[size], std::default_delete<int[]>());

另请注意:

  1. 你的运营商= returns什么都没有。
  2. 你不应该用下划线开始变量名。
  3. 不必在 class 析构函数中为 _arr 调用 reset()