【发布时间】:2020-10-27 15:08:12
【问题描述】:
在下面的代码中,当使用std::make_unique() 分配demo[] 数组时,有什么方法可以将参数传递给demo 构造函数?
class demo{
public:
int info;
demo():info(-99){} // default value
demo(int info): info(info){}
};
int main(){
// ok below code creates default constructor, totally fine, no problem
std::unique_ptr<demo> pt1 = std::make_unique<demo>();
// and this line creates argument constructor, totally fine, no problem
std::unique_ptr<demo> pt2 = std::make_unique<demo>(1800);
// But now, look at this below line
// it creates 5 object of demo class with default constructor
std::unique_ptr<demo[]> pt3 = std::make_unique<demo[]>(5);
// but I need here to pass second constructor argument, something like this : -
//std::unique_ptr<demo[]> pt3 = std::make_unique<demo[]>(5, 200);
return 0;
}
【问题讨论】:
-
改用
std::vector。 -
除此之外:从标题来看,我期待的是
std::unique_ptr<demo>[],而不是std::unique_ptr<demo[]>