1

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

我写了这段代码:

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>          ]

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

4

3 回答 3

3

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

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

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

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

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

于 2013-02-10T15:30:21.170 回答
2

这条线Text text();没有做你认为它做的事情。

它将它解析为一个名为的函数text的声明,该函数不接受任何参数并返回一个 type 的值Text

这就是您的行pText.reset(&text);无法编译的原因。

但是,您确实希望编译该行:您正在将一个shared_ptr对象与具有自动存储持续时间的值相关联:当shared_ptr超出范围时,它将尝试delete该对象,导致未定义的行为(很可能在这个案例)。

于 2013-02-10T15:29:02.950 回答
0

main的功能应该读。

int main()
{
    shared_ptr<Text> pText(new Text);
    return 0;
}

你有2个问题。首先,Text text()被解析为函数声明。其次,您将堆栈变量的地址传递给 a ,当引用计数达到 0 时shared_ptr,它将成为对象。delete

您还应该考虑是否需要使用shared_ptr. 您是否会与其他任何主体共享此指针,或者您只是想确保它被正确销毁?你可以考虑unique_ptr后一种情况。你甚至需要一个指针,你能在堆栈上分配对象吗?

于 2013-02-10T15:31:19.190 回答