ptr_vector未正确释放
ptr_vector is not freed properly
我正在尝试使用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).
我做错了什么?谢谢!
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
是完全没有必要的。
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;
}
如果您不打算将指针推回其中,则使用ptr_vector是没有意义的。
要么使用 std::vector,要么推回使用 new 关键字分配的字符串。
相关文章:
- std::vector move 而不是交换到空 vector 并释放存储
- AddressSanitizer 将 std::vector<T>::p ush_back 标识为释放后堆使用错误的原因
- 释放 std::vector 中指针内存的最有效方法是什么?
- 释放 std::vector 中的内存
- 删除[]是否可以与通用数组正常使用?如果是这样,为什么使用std :: vector ::擦除它会导致释放内存的错误
- pybind11和std :: vector-如何使用胶囊释放数据
- vector clear()似乎无法释放push_back中分配的内存
- 在 std::vector 中释放内存
- 为什么在我的机器上std::vector的分配和释放比动态数组慢
- 通过在c++中删除vector中的vector来释放内存
- 将 std::vector 截断<char>为长度 N - 以释放内存的有效方法
- 为什么std::vector没有释放方法
- 在std: vector中擦除,调试,释放
- std::vector的boost::shared_ptr的内存释放
- 如果没有堆内存,如何释放std::vector
- 释放std::vector的内存
- 是否保证std::vector每次使用allocate函数分配的内存,也会通过单个deallocate调用立即释放?
- STL vector.clear()导致内存双元释放或pthreads程序损坏
- 完全释放std::vector容器的内存
- std::shared_ptr类型的Vector不能释放内存