在C ++中创建一个向量的shared_ptr [英] Creating a shared_ptr of vector in C++

查看:146
本文介绍了在C ++中创建一个向量的shared_ptr的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在现代C ++中,我们可以这样初始化一个向量:

  std :: vector< int& v = {1,2,3,4,5}; 

但是如果我尝试创建一个向量的智能指针, >

  auto v = std :: make_shared< std :: vector< int>>({1,2,3,4,5} ); 

除了使用 push_back

$

  auto v = std :: make_shared< std :: vector< int>>(std :: initializer_list< int> {1,2,3,4,5}); 

这是工作。看起来编译器不能在make_unique params中使用{}而没有直接指定initializer_list。



编辑 - 使用MSVC 2015


In modern C++ we can initialize a vector like this:

std::vector<int> v = { 1, 2, 3, 4, 5 };

But if I try creating a smart pointer to a vector, this won't compile:

auto v = std::make_shared<std::vector<int>>({ 1, 2, 3, 4, 5 });

Is there any better alternative than resorting to push_backs after creation?

解决方案

auto v = std::make_shared<std::vector<int>>(std::initializer_list<int>{ 1, 2, 3, 4, 5 });

This is working. Looks like compiler cannot eat {} in make_unique params without direct specification of initializer_list.

Minor edit - used MSVC 2015

这篇关于在C ++中创建一个向量的shared_ptr的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆