【问题标题】:How to return an object on the heap in c++?如何在 C++ 中返回堆上的对象?
【发布时间】:2014-10-03 18:22:57
【问题描述】:

目前我有两个计划,要么返回对象本身,

std::vector<std::vector<std::string> > myfunc()

    // initialize a 2d vector (matrix) with fixed size
    std::vector<std::vector<std::string> > *res = new std::vector<std::vector<std::string> > (nc, std::vector<std::string>(nr));

    // fill res up with some operations

    return *res;
}


int main(int argc, char const* argv[])
{
    std::vector<std::vector<std::string> > x = myfunc()
    // do something with x
    return 0;
}

或者返回一个指针:

std::vector<std::vector<std::string> >* myfunc()

    // initialize a 2d vector (matrix) with fixed size
    std::vector<std::vector<std::string> > *res = new std::vector<std::vector<std::string> > (nc, std::vector<std::string>(nr));

    // fill res up with some operations

    return res;
}


int main(int argc, char const* argv[])
{
    std::vector<std::vector<std::string> >* x = myfunc()
    // do something with x
    return 0;
}

但我的直觉告诉我他们两个都有问题。有什么建议吗?

【问题讨论】:

  • 您需要使用new的任何特殊原因?为什么不直接创建一个对象,然后按值返回呢?

标签: c++ return heap-memory


【解决方案1】:

第一种情况不好。您有内存泄漏。

第二种情况更好。您可以选择释放内存。最好使用智能指针:std::shared_ptrstd::unique_ptr

std::shared_ptr<std::vector<std::vector<std::string>>> myfunc()
{    
    // initialize a 2d vector (matrix) with fixed size
    std::vector<std::vector<std::string> > *res = new std::vector<std::vector<std::string> > (nc, std::vector<std::string>(nr));

    // fill res up with some operations

    return std::shared_ptr<std::vector<std::vector<std::string>>>(res);
}

std::unique_ptr<std::vector<std::vector<std::string>>> myfunc()
{
    // initialize a 2d vector (matrix) with fixed size
    std::vector<std::vector<std::string> > *res = new std::vector<std::vector<std::string> > (nc, std::vector<std::string>(nr));

    // fill res up with some operations

    return std::unique_ptr<std::vector<std::vector<std::string>>>(res);
}

【讨论】:

  • @qed,是的。在en.cppreference.com/w/cpp/memory/unique_ptr查看示例代码。
  • 但是我怎么会得到这个错误:从 'std::vector<:vector> > *' 到 'std::unique_ptr<:vector> > >'
  • @qed,我的错。必须更改 return 语句以显式构造 unique_ptr。查看更新的答案。
  • 很好,谢谢。这意味着我不必担心释放内存对吗?
【解决方案2】:

如果向量需要在堆上 - 使用 shared_ptrs,或者,避免一起使用 ptrs;在main中构造vector,并通过引用传递给函数。

查看C++ return value optimization

【讨论】:

    猜你喜欢
    • 2015-04-23
    • 2020-02-18
    • 2011-11-17
    • 1970-01-01
    • 2016-02-04
    • 2011-03-21
    • 2012-07-24
    • 2010-09-17
    相关资源
    最近更新 更多