#include <iostream> #include <string> #include <vector> std::shared_ptr<std::vector<std::string>> AssignValue() { std::vector<std::string> str_v1; std::string s1 = "hello"; std::string s2 = "world"; str_v1.push_back(s1); str_v1.push_back(s2); // std::make_shared 自动分配内存 auto make_ptr_1 = std::make_shared<std::vector<std::string>>(str_v1); // 栈分配 // std::shared_ptr<std::vector<std::string>>make_ptr_1(&str_v1); return make_ptr_1; } int main() { std::shared_ptr<std::vector<std::string>> make_ptr_2(AssignValue()); // 效果一样 // make_ptr_2 = AssignValue(); auto count = make_ptr_2.get()->size(); auto refer_num = make_ptr_2.use_count(); /* 下面注释的代码看看就好 std::vector<std::string> *copy_v2 = make_ptr_2.get(); std::cout << copy_v2[0].data()[0] << std::endl; std::cout << copy_v2[0].data()[1] << std::endl; */ for (int i = 0; i < count; i++) { std::cout << make_ptr_2 << std::endl; // 带不带 get() 都能返回指针地址 std::cout << make_ptr_2->data()[i].c_str() << std::endl; std::cout << make_ptr_2.get()->data()[i].c_str() << std::endl; } return 0; }
最后输出:
原文链接: https://www.cnblogs.com/strive-sun/p/15713532.html
欢迎关注
微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍;
也有高质量的技术群,里面有嵌入式、搜广推等BAT大佬
原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/404584
非原创文章文中已经注明原地址,如有侵权,联系删除
关注公众号【高性能架构探索】,第一时间获取最新文章
转载文章受原作者版权保护。转载请注明原作者出处!