如何解决我需要将对象向量或括号括起来的列表传递给构造函数的选项
我的构造函数最初使用的是std::vector<>
,但是我不知道如何获得支撑列表来对其进行初始化。更改为std:initializer_list<>
后,我开始使用它。我发现了两种方法:1)将initializer_list作为参数传递给数组构造函数(在下面的代码中进行了注释),以及2)使用std::copy
算法(在下面的代码中看到)。
现在,我需要使用std::vector<>
创建该对象,并且无法弄清楚如何将其转换为initializer_list。我可以使第二个构造函数使用一个向量,但是作为练习,我希望在可能的情况下使用一个构造函数。
有什么想法吗?
class One: public Base {
public:
One( Two* ptwo_in,std::initializer_list<Three> ilthree ) :
ptwo( ptwo_in )//,//athree_( ilthree )
{
athree_.reserve( ilthree .size() );
std::copy( ilthree .begin(),ilthree .end(),athree_.begin() );
}
Two* ptwo_;
std::vector<Three> athree_;
};
// Works fine:
new One( &two,{ Three( args ),Three( args ),} )
// Doesn't work:
std::vector<Three>* pathreeSomething
athreeOther.push_back( new One( ptwoLocal,*pathreeSomething ) );
解决方法
在第三行代码中,它可以将vector_true替换为initializer_list。但我不想将整个向量作为arg传递。
无论如何,您都要构造一个向量(One::athree_
)。因此,只需将传递给构造函数的向量移动,而不是复制它:
class One: public Base {
public:
One(Two* ptwo_in,std::vector<Three> ilthree)
: ptwo{ptwo_in},athree_{std::move(ilthree)}
{ }
private:
Two* ptwo_;
std::vector<Three> athree_;
};
这是C ++中的常见模式。传递非const值并使用move语义避免复制:
One one{some_ptr,{Three{args},Three{args},Three{args}}};
或:
std::vector<Three> vec{ ... };
// moves 'vec' to the ctor parameter,the ctor then moves it to its member
One one{some_ptr,std::move(vec)};
没有那种不必要的副本。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。