auto关键字与智能指针一起使用?

3
我可以:
auto o1 = new Content;

但是不能:
std::shared_ptr<auto> o1(new Content);
std::unique_ptr<auto> o1(new Content);

我该怎么做?


7
auto o1 = make_unique<Content>(); - tkausl
2
请注意,您不能编写std::shared_ptr o1(new Content);。一般情况下,当模板参数可以推断时,现在可以省略它,但是仅凭一个T*无法选择shared_ptr<Content[]>shared_ptr<Content>之间的区别。(详细信息请搜索“C++模板推断指南”) - MSalters
2个回答

3
你可以像这样使用make_shared/make_unique:
auto o1 = std::make_shared<Content>(); // Pass any arguments here as you would normally.
auto o2 = std::make_unique<Content>(); // Pass any arguments here as you would normally.

这些函数将所有参数转发到(在本例中)Content 的构造函数中,您可以使用 auto 并且只需要写一次类型。


2

您应该:

auto o1 = std::make_unique<Content>();
auto o2 = std::make_shared<Content>();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接