gpt4 book ai didi

c++ - 如何实例化一个全局智能指针变量?

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:24:59 24 4
gpt4 key购买 nike

如何实例化

unique_ptr<int[]> sums;

int main(int argc, char** argv)
{
int n = //get from args
sums(new int[n]);
}

?它给了我以下编译时错误

error C2247: 'std::default_delete<_Ty>::operator ()' not accessible because 'std::unique_ptr>' uses 'private' to inherit from 'std::_Unique_ptr_base<_Ty,_Dx,true>'

最佳答案

看起来您可能对 C++ 的构造函数调用语法感到困惑。

如果你说

unique_ptr<int[]> sums(new int[n]);

构造一个名为 sums 的新对象, 使用指向 int 数组的指针调用构造函数。

如果你说

unique_ptr<int[]> sums;
sums(new int[n]);

它构造sums在第一行使用 0 参数构造函数,然后在第二行尝试调用 unique_ptr<int[]>::operator()(int*) (即函数调用运算符)在 sums 上目的。这不存在,这给了你错误。

正如 dauphic 的回答所说,您要查找的函数称为 reset :

sums.reset(new int[n]);

(您可能想知道为什么存在像函数调用运算符这样愚蠢的东西。它允许您创建 an object that can be called like a function, but passed around like a value. )

关于c++ - 如何实例化一个全局智能指针变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19867360/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com