[英]Returning a shared_ptr
我有一个需要返回另一个类的新对象的函数,所以我想我需要将其返回对象保存在共享指针中。 像这样
X班
Y* func(param)
{
return new Y(param);
}
我尝试将其更改为
std::shared_ptr<Y> func(param)
{
std::shared_ptr<Y> y(new Y(param));
return y;
}
我不想返回本地对象,那么该怎么办?
我建议您将std::shared_ptr
作为返回类型,并return std::make_shared<Y>()
以转让所有权。
这是一个可能会帮助您的工作示例:
#include <memory>
#include <iostream>
#include <string>
class Y {
public:
Y(const std::string& n)
: name{n} {}
std::string name;
};
std::shared_ptr<Y> func()
{
return std::make_shared<Y>("new class");
}
int main()
{
std::shared_ptr<Y> p_class = func();
std::cout << p_class->name;
// outputs: "new class"
return 0;
}
您返回一个堆分配的对象,这意味着您转移所有权。 我建议您使用std::unique_ptr
作为返回类型
std::unique_ptr<Y> func(param)
{
return std::unique_ptr<Y>(new Y(param));
}
更好的方法是使用std :: make_unique(如果已经可用,否则编写您自己的)或-如果您使用shared_ptr-std :: make_shared。 对于异常安全性和在shared_ptr效率更高的情况下,这样做更好。
std::unique_ptr<Y> func(param)
{
return make_unique<Y>(param);
}
std::shared_ptr<Y> func(param)
{
return std::shared_ptr<Y>(param);
}
并且请注意,您的func
复制了参数。 您可能需要使用转发来避免这种情况。
template<class T, class U>
std::unique_ptr<T> make_unique1(U&& u)
{
return std::unique_ptr<T>(new T(std::forward<U>(u)));
}
template<class T, class... U>
std::unique_ptr<T> make_unique(U&&... u)
{
return std::unique_ptr<T>(new T(std::forward<U>(u)...));
}
除了我的建议std::unique_ptr
答案外,我想指出的是,不必在堆上创建对象以从函数返回它。 您可以按值返回新对象:
Y func(param)
{
Y result(param);
return result;
}
如果Y
是可复制的,这将(并且一直有效)起作用。 如果该类不可复制,它将无法工作;如果有效,则可能涉及复制对象。
尽管大多数编译器多年来都没有删除该副本,但是如果您返回未命名的临时对象,则标准C++17
现在必须这样做。 这意味着即使您有不可复制且不可移动的对象,以下代码也将编译并返回一个新对象:
class Y {
public:
Y(int i): value(i) {}
Y(Y const&) = delete;
Y(Y&&) = delete;
Y& operator=(Y const&) = delete;
Y& operator=(Y&&) = delete;
int value;
};
Y foo(int i) {
return Y(i);
}
void bar {
Y y = foo(42);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.