gpt4 book ai didi

c++ - std::vector - 错误:无法删除不是指针的对象

转载 作者:行者123 更新时间:2023-11-30 01:23:34 24 4
gpt4 key购买 nike

也许有人可以帮助我理解错误。

我写这段代码:

class Text
{
private:
struct paragraph
{
vector<string> lines;
};

vector<shared_ptr<paragraph>> paragraphs;
public:

Text()
{
paragraphs.push_back(shared_ptr<paragraph>(new paragraph()));
}
};

int main()
{
shared_ptr<Text> pText(nullptr);
Text text();
pText.reset(&text);
return 0;
}

当我尝试运行它时
我收到此错误:

    1>c:\program files\microsoft visual studio 10.0\vc\include\memory(1664): error C2541: 'delete' : cannot delete objects that are not pointers
1> c:\program files\microsoft visual studio 10.0\vc\include\memory(1431) : see reference to function template instantiation 'void std::tr1::shared_ptr<_Ty>::_Resetp<_Ux>(_Ux (__cdecl *))' being compiled
1> with
1> [
1> _Ty=Text,
1> _Ux=Text (void)
1> ]
1> c:\program files\microsoft visual studio 10.0\vc\include\memory(1607) : see reference to function template instantiation 'std::tr1::shared_ptr<_Ty>::shared_ptr<_Ux>(_Ux (__cdecl *))' being compiled
1> with
1> [
1> _Ty=Text,
1> _Ux=Text (void)
1> ]
1> c:\documents and settings\owner\שולחן העבודה\e\class.cpp(29) : see reference to function template instantiation 'void std::tr1::shared_ptr<_Ty>::reset<Text(void)>(_Ux (__cdecl *))' being compiled
1> with
1> [
1> _Ty=Text,
1> _Ux=Text (void)
1> ]

“不能删除不是指针的对象”是什么意思?
我不是要删除任何对象。

最佳答案

除了最令人烦恼的解析之外,您的代码还包含一个基本缺陷:

您不得将指向堆栈分配对象的指针分配给 shared_ptr

此代码将导致未定义的行为,这在实践中意味着很多痛苦:

shared_ptr<Text> pText(nullptr);
Text text;
pText.reset(&text);

shared_ptr 将在其生命周期结束时尝试delete &text

关于c++ - std::vector - 错误:无法删除不是指针的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14799277/

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