在不创建副本的情况下从函数返回的最简单方法 [英] Simplest way of returning from a function without creating a copy

查看:72
本文介绍了在不创建副本的情况下从函数返回的最简单方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚进入移动语义,从我的阅读中,它只适用于一个类' new 的内容。我是否遗漏了某些东西,或者这样做是否如此,如果我想在从函数返回时消除元素的复制,一种方法是使用 std :: unique_ptr ?例如,给定 struct



I'm just getting into move semantics, and from my reading it is only useful when a class 'new's something within it. Am I missing something, or does that make it so that if I want to eliminate the copying of an element upon returning from a function, one way to do so is to use a std::unique_ptr? For example, given the struct:

struct Triangle {
   POINT p1;
   POINT p2;
   POINT p3;
   };





如果我想从创建一个函数的函数返回,最好的方法就是如下:





If I want to return from a function that creates one, the best way to do so is something like the following:

std:unique_ptr<MouseHelper::Triangle> MouseHelper::makeTrianglePointingDown(int x, int y) {
   //The following is hard coded for the sizes I'm using in the example
   const int halfSize = 5;
   std:unique_ptr<Triangle> t(new Triangle);
   t->p1.x = x-halfSize;
   t->p1.y = y-halfSize-halfSize;

   t->p2.x = x+halfSize;
   t->p2.y = y-halfSize-halfSize;

   t->p3.x = x;
   t->p3.y = y-2;

   return t;
   }





否则,我必须将' Triangle '变成'一个类, new 该类中的结构,然后创建一个合适的移动构造函数?



谢谢!



我的尝试:



阅读。上面的代码可以工作。



Otherwise, I must make 'Triangle' into a class, and new a structure within that class, and then create an appropriate move constructor?

Thanks!

What I have tried:

Reading. And the above code works.

推荐答案

最简单的方法是按值返回对象,编译器优化它(NRVO)。

试试

The simplest way is returning the object by value, the compiler optimizes that (NRVO).
Try
#include <iostream>
using namespace std;

struct Point
{
  int x, y;
};

struct Triangle
{
  Point p1,p2,p3;
  Triangle(){cout << "Triangle ctor" << endl;}
};

Triangle makeTrianglePointingDown(int x, int y)
{
   const int halfSize = 5;

   Triangle t;
   t.p1.x = x-halfSize;
   t.p1.y = y-halfSize-halfSize;

   t.p2.x = x+halfSize;
   t.p2.y = y-halfSize-halfSize;

   t.p3.x = x;
   t.p3.y = y-2;

   return t;
}

int main()
{
  Triangle tpd  = makeTrianglePointingDown(10,10);
  cout << tpd.p1.x << " " << tpd.p1.y << " ";
  cout << tpd.p2.x << " " << tpd.p2.y << " ";
  cout << tpd.p3.x << " " << tpd.p3.y << endl;
}


如果你想要动态内存分配,是的unique_ptr可以是解决方案。

但即使你只是从函数返回函数局部结构变量,这可以在不复制的情况下完成。调用者函数可以预先分配堆栈空间,而被调用者只会填充此空间。并且在没有复制的情况下,将在调用后使用此内存块。
If you want dynamic memory allocation, yes unique_ptr can be the solution.
But even if you simply return function local structure variable from the function, this can be done without a copying. Caller function can pre-allocate stack space and callee will just fill this space. And this memory block will be used after the call without a copying.


这篇关于在不创建副本的情况下从函数返回的最简单方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆