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总结与使用


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM