std::shared_ptr 和 std::vector 的结合使用

#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;
}

  

最后输出:

 

 相关资料:C++11 std::shared_ptr总结与使用

posted @ 2021-12-21 00:06  strive-sun  阅读(3875)  评论(0编辑  收藏  举报