unique_ptr作为类成员并在vector中传递的问题

HollyCpp HollyCpp 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
如下,我把shared_ptr改成unique_ptr,就不能直接在vector中push_back了,C++11新手,这里该怎么改正?


#include <iostream>
#include <string>
#include <memory>
#include <vector>

using namespace std;

class Person
{
public:
Person(string name) : pName(new string(name)){}
~Person(){}
void printName() { cout << *pName << endl; }


private:
unique_ptr<string> pName;
//shared_ptr<string> pName;
};

int main()
{
vector<Person> persons;

Person p("George");
persons.push_back(p);
persons.front().printName();

cout << "==========\n";

return 0;
}
...全文
评论 2
收藏 已收藏
分享
返回顶部
HollyCpp
C++ 语言 65,213 成员 250,513 内容