C ++使用裸机代替智能指针

时间:2019-12-11 10:33:05

标签: c++ 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中的值。据我了解,智能指针对这项任务不利。在这里使用裸露的指针,可以接受的替代方法吗?

1 个答案:

答案 0 :(得分:2)

make_shared并不意味着“共享已存在的内容”。

这意味着“使用以下构造函数参数创建共享的新事物”。

您正在动态分配一个用于复制vec[0]的新字符串(即使用复制构造函数)。

如果您希望vec[0]成为shared_ptr<string>,则需要从一开始就将其设置为一个。

相关问题