我很新c ,我被困在這個問題上。我將一個結構指標(Bar *)附加到一個向量,并且該結構有一個指標類成員(Foo *)。
struct Bar
{
const int var{ 0 };
Foo* m_foo{ nullptr };
};
std::vector<Bar*> list;
int main()
{
Bar* p_Bar = new Bar;
p_Bar->m_foo = new Foo;
list.emplace_back(p_Bar);
}
我有一個執行緒來檢查這些指標的有效性。一旦我洗掉了這些指標,向量元素應該存在,我應該檢查兩個指標??是否有效。當其中任何一個無效時,我應該洗掉該向量元素(我的意思是檢查后)。這是我的嘗試:
#include <iostream>
#include <vector>
#include <thread>
class Foo
{
public:
Foo() {};
const int var{ 5 };
};
struct Bar
{
const int var{ 0 };
Foo* m_foo{ nullptr };
};
std::vector<Bar*> list;
bool _check = true;
void Check()
{
while (_check)
{
for (int c = 0; c < (int)list.size(); c )
{
Bar* p = list[c];
if (p)
{
if (p->m_foo)
{
std::cout << "m_foo->var:" << p->m_foo->var << "\nEnter anything to delete the element: ";
}
else
{
std::cout << "m_foo was nullptr";
}
}
else
{
std::cout << "Element was invalid";
}
}
std::this_thread::sleep_for(std::chrono::duration(std::chrono::seconds(2)));
}
}
int main()
{
Bar* p_Bar = new Bar;
p_Bar->m_foo = new Foo;
list.emplace_back(p_Bar);
std::thread thread1(Check);
thread1.detach();
std::string t;
std::cin >> t;
if (list[0]->m_foo)
delete list[0]->m_foo;
if (list[0])
delete list[0];
list.clear();
std::cin >> t;
_check = false;
return 0;
}
要檢查指標是否被洗掉,我應該使用NULLornullptr這實際上表示 0。但是一旦指標被洗掉,地址將類似于 0xFFFFFFFFFFFFFFFF 并且 IDE 會拋出這種例外:
Exception thrown: read access violation.
p->m_foo was 0xFFFFFFFFFFFFFFFF.
如何檢查指標的洗掉/指標地址是否有效?
uj5u.com熱心網友回復:
如何檢查指標的洗掉/指標地址是否有效?
無法檢查指標是否有效。如果指標有效或為空,那么您可以檢查它是哪一個。如果指標無效,則比較的結果將是未指定的。
除了比較無效指標之外,您的程式還有另一個錯誤:您在一個執行緒中洗掉,并在另一個執行緒中訪問指標而不同步操作。同樣,您正在訪問向量的元素,而它的元素在另一個執行緒中被洗掉。程式的行為是未定義的。
PS 避免擁有裸指標。
uj5u.com熱心網友回復:
您可以使用 automatic_ptr 類而不是經典的內置指標。您可以自己開發,或使用例如。std::unique_ptr 和 std::shared_ptr。此類的原則是,該指標包含在類中,并且類計數外部鏈接(指標...)并將其存盤到內部屬性中。在每本書的 C 中都有它的例子。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/443093.html
