使用自定义对象声明 shared_ptr 的数组时出现错误 C2664
Error C2664 when declaring an array of shared_ptr with a custom object
我在使用时总是出错:
std::shared_ptr<ModelType> out(new shared_ptr<ModelType>[m_MAX]);
实例化shared_ptr的数组是不是正确的方法?
错误如下:
error C2664: 'void std::_Ptr_base<_Ty>::_Reset0(_Ty *,std::_Ref_count_base *)': 无法将参数 1 从 'std::shared_ptr *' 转换为 'ModelType *'
提前致谢
你不能像 C++11 和 C++14 标准中的 std::shared_ptr<T[]>
这样的共享指针有数组类型,所以你不能将智能指针分配给数组。您可以做的是从指向数组的唯一指针构造一个:
#include <iostream>
#include <memory>
class ModelType{
};
int main(){
const int M_MAX = 123;
std::unique_ptr<ModelType[]> arr(new ModelType[M_MAX]);
std::shared_ptr<ModelType> ptr(std::move(arr));
}
然而,在 C++17 标准中,可以使用指向数组类型的共享指针,如 std::shared_ptr 文档中所述,因此您可以拥有:
std::shared_ptr<ModelType[]> arr(new ModelType[M_MAX]);
Live example.
更喜欢 std::make_shared or in your case the boost::make_shared 而不是直接使用 new
.
我在使用时总是出错:
std::shared_ptr<ModelType> out(new shared_ptr<ModelType>[m_MAX]);
实例化shared_ptr的数组是不是正确的方法? 错误如下:
error C2664: 'void std::_Ptr_base<_Ty>::_Reset0(_Ty *,std::_Ref_count_base *)': 无法将参数 1 从 'std::shared_ptr *' 转换为 'ModelType *'
提前致谢
你不能像 C++11 和 C++14 标准中的 std::shared_ptr<T[]>
这样的共享指针有数组类型,所以你不能将智能指针分配给数组。您可以做的是从指向数组的唯一指针构造一个:
#include <iostream>
#include <memory>
class ModelType{
};
int main(){
const int M_MAX = 123;
std::unique_ptr<ModelType[]> arr(new ModelType[M_MAX]);
std::shared_ptr<ModelType> ptr(std::move(arr));
}
然而,在 C++17 标准中,可以使用指向数组类型的共享指针,如 std::shared_ptr 文档中所述,因此您可以拥有:
std::shared_ptr<ModelType[]> arr(new ModelType[M_MAX]);
Live example.
更喜欢 std::make_shared or in your case the boost::make_shared 而不是直接使用 new
.