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

HollyCpp 2016-01-09 07:19:32
如下,我把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;
}
...全文
448 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
fefe82 2016-01-09
  • 打赏
  • 举报
回复
VS2013 能否支持不清楚,但 unique_ptr 要: push_back(std::move(p)); 你需要自己写一个 move constructor: Person(Person&&p):pName(std::move(p.pName)){}
HollyCpp 2016-01-09
  • 打赏
  • 举报
回复
顺便一说,测试环境是VS2013,错误提示是什么
error C2280......attempting to reference a deleted function

64,683

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧