#1、error: 'shared_ptr' was not declared in this scope
1 #include <iostream>
2 #include <memory>
3 using namespace std;
4 int main()
5 {
6 shared_ptr<int> p1 = make_shared<int>();
7 *p1 = 10;
8 cout << "p1="<<*p1<<endl;
9 }
root@mkx:~/learn/share_ptr# g++ test2.cpp -o test2
test2.cpp: In function ‘int main()’:
test2.cpp:6:3: error: ‘shared_ptr’ was not declared in this scope
shared_ptr<int> p1 = make_shared<int>();
^
test2.cpp:6:14: error: expected primary-expression before ‘int’
shared_ptr<int> p1 = make_shared<int>();
^
test2.cpp:7:4: error: ‘p1’ was not declared in this scope
*p1 = 10;
^
root@mkx:~/learn/share_ptr#
#2、因为shared_ptr是C++11的特性
1、You need to add the memory header at the beginning of your file.
#include <memory>
2、if above solution does not work even after include of header, please ensure that to compiler you are passing argument --std=c++11
中文的介绍:
shared_ptr 是C++11提供的一种智能指针类,它足够智能,可以在任何地方都不使用时自动删除相关指针,从而帮助彻底消除内存泄漏和悬空指针的问题。
它遵循共享所有权的概念,即不同的 shared_ptr 对象可以与相同的指针相关联,并在内部使用引用计数机制来实现这一点。
#3、指定C++标准版本就可以了
root@mkx:~/learn/share_ptr# g++ -std=c++11 test2.cpp -o test2
root@mkx:~/learn/share_ptr# ./test2
p1=10
root@mkx:~/learn/share_ptr#