[英]C++ Using naked, instead of smart pointers
考虑以下代码。
#include <iostream>
#include <vector>
#include <memory>
int main() {
std::vector<std::string> vec;
for(int i =0;i<10;i++){
vec.push_back("adsf");
}
std::string* myPoint = &vec[1];
*myPoint = "this works";
std::shared_ptr<std::string> str_ptr = std::make_shared<std::string>(vec[0]);
str_ptr->push_back('this does not push_back to the end of the string stored in at vec[0]');
for(int i =0;i<10;i++){
std::cout << vec[i] << std::endl; //does not print the new value set by str_ptr
}
return 0;
}
我在这里想要的是通过指针更新vec
的值。 据我所知,智能指针不适合这项任务。 在这里使用裸指针是一种可以接受的替代方法吗?
make_shared
并不意味着“让这个已经存在的东西被共享”。
这意味着“使用以下构造函数参数创建一个新的共享事物”。
您正在动态分配一个复制vec[0]
的新字符串(即使用复制构造函数)。
如果您希望vec[0]
成为shared_ptr<string>
,那么您需要从一开始就将其设为一个。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.