1

ptr_vector を使用していくつかのポインターを格納しようとしていますが、メイン メソッドを実行するとすぐにエラーが発生します。これが私のコードです:

int main(void)
{
    boost::ptr_vector<string> temp;
    string s1 = "hi";
    string s2 = "hello";
    temp.push_back(&s1);
    temp.push_back(&s2);
    return 0;
}

これは私が得ているエラーメッセージです:

Critical error detected c0000374
Windows has triggered a breakpoint in Path_Tree.exe.

This may be due to a corruption of the heap, which indicates a bug in Path_Tree.exe or     any of the DLLs it has loaded.

This may also be due to the user pressing F12 while Path_Tree.exe has focus.

The output window may have more diagnostic information.
The program '[7344] Path_Tree.exe: Native' has exited with code 0 (0x0).

私は何を間違っていますか?ありがとう!

4

3 に答える 3

10

ptr_vectorあなたがそれに与えたポインタが指すオブジェクトの所有権を取得します(つまり、deleteそれらのポインタを使い終わったときにそれらのポインタを呼び出すことを意味します)。ポインターのベクトルだけが必要な場合は、次を使用します。

int main()
{
    std::vector<string*> temp;
    //s1 and s2 manage their own lifetimes
    //(and will be destructed at the end of the scope)
    string s1 = "hi";
    string s2 = "hello";
    //temp[0] and temp[1] point to s1 and s2 respectively
    temp.push_back(&s1);
    temp.push_back(&s2);
    return 0;
}

それ以外の場合は、new を使用して文字列を割り当て、結果のポインターを push_back する必要があります。

int main()
{
    boost::ptr_vector<string> temp;
    temp.push_back(new string("hi"));
    temp.push_back(new string("hello"));
    return 0;
}

文字列のコンテナだけが必要な場合、通常は文字列のベクトルになります。

int main()
{
    std::vector<string> temp;
    //s1 and s2 manage their own lifetimes
    //(and will be destructed at the end of the scope)
    string s1 = "hi";
    string s2 = "hello";
    //temp[0] and temp[1] refer to copies of s1 and s2.
    //The vector manages the lifetimes of these copies,
    //and will destroy them when it goes out of scope.
    temp.push_back(s1);
    temp.push_back(s2);
    return 0;
}

ptr_vector値のセマンティクスを持つポリモーフィック オブジェクトを簡単に作成できるようにすることを目的としています。そもそも文字列がポリモーフィックでない場合ptr_vectorは、まったく不要です。

于 2012-08-15T15:20:46.080 に答える
1

ptr_vector動的に割り当てられたオブジェクトへのポインターを格納するように設計されています。その後、それらの所有権を取得し、存続期間の終わりにそれらを削除します。削除できないオブジェクトへのポインターを渡すと、未定義の動作が発生します。

int main(void)
{
    boost::ptr_vector<std::string> temp;
    temp.push_back(new std::string("hi"));
    temp.push_back(new std::string("hello"));
    return 0;
}
于 2012-08-15T15:20:02.960 に答える
0

ポインターをプッシュバックしない場合は、ptr_vector を使用しても意味がありません。

std::vector を使用するか、 new キーワードで割り当てられた文字列をプッシュ バックします。

于 2012-08-15T15:21:34.533 に答える