我可以:
但是不能:
auto o1 = new Content;
但是不能:
std::shared_ptr<auto> o1(new Content);
std::unique_ptr<auto> o1(new Content);
我该怎么做?
auto o1 = new Content;
std::shared_ptr<auto> o1(new Content);
std::unique_ptr<auto> o1(new Content);
我该怎么做?
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
并且只需要写一次类型。
您应该:
auto o1 = std::make_unique<Content>();
auto o2 = std::make_shared<Content>();
auto o1 = make_unique<Content>();
? - tkauslstd::shared_ptr o1(new Content);
。一般情况下,当模板参数可以推断时,现在可以省略它,但是仅凭一个T*
无法选择shared_ptr<Content[]>
和shared_ptr<Content>
之间的区别。(详细信息请搜索“C++模板推断指南”) - MSalters