sub*_*bha 0 c++ g++ smart-pointers c++11
请找到我从https://www.geeksforgeeks.org/auto_ptr-unique_ptr-shared_ptr-weak_ptr-2/获取的用于测试智能指针的代码。
// C++ program to demonstrate shared_ptr
#include <iostream>
#include <memory>
class A {
public:
void show()
{
std::cout << "A::show()" << std::endl;
}
};
int main()
{
std::shared_ptr<A> p1(new A);
std::cout << p1.get() << std::endl;
p1->show();
std::shared_ptr<A> p2(p1);
p2->show();
std::cout << p1.get() << std::endl;
std::cout << p2.get() << std::endl;
// Returns the number of shared_ptr objects
// referring to the same managed object.
std::cout << p1.use_count() << std::endl;
std::cout << p2.use_count() << std::endl;
// Relinquishes ownership of p1 on the object
// and pointer becomes NULL
p1.reset();
std::cout << p1.get() << std::endl;
std::cout << p2.use_count() << std::endl;
std::cout << p2.get() << std::endl;
p1->show();
p2->show();
std::cout << p1.get() << std::endl;
std::cout << p2.use_count() << std::endl;
std::cout << p2.get() << std::endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
p1 被重置并且没有指针分配给它(根据 p1.get() 找到)。之后,当我调用 p1->show() 函数时,它将输出显示为 A::show()。怎么可能呢?原始指针也是同样的情况吗?
output:
0x24dc5ef1790
A::show()
A::show()
0x24dc5ef1790
0x24dc5ef1790
2
2
0
1
0x24dc5ef1790
A::show()
A::show()
0
1
0x24dc5ef1790
Run Code Online (Sandbox Code Playgroud)
它之所以有效,是因为您没有使用对象中的任何成员,否则会出现段错误。但消毒剂很容易发现这个问题:
$ g++ -ggdb -O0 -fsanitize=undefined,address shared.cpp -o shared
$ ./shared
0x602000000010
A::show()
A::show()
0x602000000010
0x602000000010
2
2
0
1
0x602000000010
shared.cpp:33:13: runtime error: member call on null pointer of type 'struct element_type'
A::show()
A::show()
0
1
0x602000000010
Run Code Online (Sandbox Code Playgroud)
更改代码以添加一个成员变量以进行打印,如下所示
class A {
public:
void show()
{
std::cout << "A::show() " << value << std::endl;
}
int value;
};
Run Code Online (Sandbox Code Playgroud)
它会出现段错误
$ g++ -ggdb -O0 shared.cpp -o shared
$ ./shared
0x560a3dde4eb0
A::show() 0
A::show() 0
0x560a3dde4eb0
0x560a3dde4eb0
2
2
0
1
0x560a3dde4eb0
Segmentation fault (core dumped)
Run Code Online (Sandbox Code Playgroud)