c++ - 返回一个 shared_ptr

标签 c++

我有一个函数需要返回另一个类的新对象,所以我想我需要将它的返回对象保存在一个共享指针中。像这样

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;
}

关于c++ - 返回一个 shared_ptr,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27561840/

相关文章:

c++ - 控制Lua5.1的垃圾收集器

c++ - DVB PSI解码

c++ - Qt C++ QLine QPoint

c++ - g++ 编译器找不到文件 cstudio.怎么了?

c++ - 为什么我的 C++ 控制台在接受用户输入时会关闭?

c++ - "carbon-copy"c++ istream?

c++ - 间歇性 "Aborted Core Dumped"。也许是 static_cast 的错?

采用继承类的 C++ 非类型模板参数

c++ - SDL2 & GDB : program received signal ?,未知信号

c++ - 跨共享库边界分配和释放内存