问题描述
我刚刚进入移动语义,从我的阅读中,它只适用于一个类' 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.
推荐答案
#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;
}
这篇关于在不创建副本的情况下从函数返回的最简单方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!