首先定義一個 shared_ptr<int> p1
接著宣告另一個 shared_ptr<const int> p2
並指向 p1
分別把值印出來
#include <iostream>
#include <memory>
int main() {
std::shared_ptr<int> p1 = std::make_shared<int>(3);
std::shared_ptr<const int> p2 = p1;
std::cout << "*p1 = " << *p1 << std::endl;
std::cout << "*p2 = " << *p2 << std::endl;
return 0;
}
output
p1 = 3
p2 = 3
表示 const shared_ptr 可以指向 shared_ptr
接著將 p1 的值改為 5 並印出來
#include <iostream>
#include <memory>
int main() {
std::shared_ptr<int> p1 = std::make_shared<int>(3);
std::shared_ptr<const int> p2 = p1;
std::cout << "p1 = " << *p1 << std::endl;
std::cout << "p2 = " << *p2 << std::endl;
+ *p1 = 5;
+ std::cout << "p1 = " << *p1 << std::endl;
+ std::cout << "p2 = " << *p2 << std::endl;
return 0;
}
output
p1 = 3
p2 = 3
p1 = 5
p2 = 5
可以發現 p2 的值也被改變,那麼 const 代表的意義是什麼呢?
嘗試更改 p2 為 6
#include <iostream>
#include <memory>
int main() {
std::shared_ptr<int> p1 = std::make_shared<int>(3);
std::shared_ptr<const int> p2 = p1;
std::cout << "p1 = " << *p1 << std::endl;
std::cout << "p2 = " << *p2 << std::endl;
*p1 = 5;
std::cout << "p1 = " << *p1 << std::endl;
std::cout << "p2 = " << *p2 << std::endl;
+ *p2 = 6;
return 0;
}
output
ERROR!
/tmp/VDwjEvjmMm.cpp: In function 'int main()':
/tmp/VDwjEvjmMm.cpp:12:9: error: assignment of read-only location '((std::__shared_ptr_access<const int, __gnu_cxx::_S_atomic, false, false>*)(& p2))->std::__shared_ptr_access<const int, __gnu_cxx::_S_atomic, false, false>::operator*()'
12 | *p2 = 6;
| ~~~~^~~
compiling failed!