没有可行的从'string *'(又名'basic_string <char> *')到'shared_ptr <string> </string> </char>的转换

时间:2015-03-08 12:33:01

标签: c++ shared-ptr smart-pointers

所以我有这段代码:

#include <iostream>
#include <list>
#include <string>
#include <memory>

using namespace std;

int main() {

    {
        shared_ptr<string> str = new string("Marius");
        cout << str + " MMG";
    }

    return 0;
}

通过编译:

clang++ -Wall -g -std=c++14 test.c++ -o test

我明白了:

test.c++:11:22: error: no viable conversion from 'string *' (aka 'basic_string<char> *') to 'shared_ptr<string>'
                shared_ptr<string> str = new string("Marius");

错误在哪里? 使用GCC我会得到同样的错误。

1 个答案:

答案 0 :(得分:6)

采用原始指针的std::shared_ptr构造函数为explicit

另请注意,没有operator=采用原始指针,因此以下无法编译:

std::shared_ptr<std::string> ptr;
ptr = new std::string{"Marius"};

要正确构建一个,有两个选项:

std::shared_ptr<std::string> ptr{new std::string{"Marius"}};

// or the (much) preferred
auto ptr = std::make_shared<std::string>("Marius");