如何避免复制时我回来 [英] How to avoid the copy when I return
问题描述
我有一个函数返回一个向量或集合:
I have a function which returns a vector or set:
set<int> foo() {
set<int> bar;
// create and massage bar
return bar;
}
set<int> afoo = foo();
在这种情况下,我在函数foo()中创建一个临时内存空间,然后
通过复制将其分配给 afoo
。我真的想避免这个副本,任何容易的方式我
可以做到这一点在C + + 11?我认为这与右值事件有关。
In this case, I create a temporary memory space in function foo(), and then
assign it to afoo
by copying. I really want to avoid this copy, any easy way I
can do this in C++11? I think this has to do with the rvalue thing.
确定,更新到问题:如果我要返回一个由自己定义的对象,
不向量或集合的东西,这是否意味着我应该定义一个移动构造函数?
像这样:
OK, update to the question: If I am going to return an object defined by myself, not the vector or set thing, does that mean I should define a move constructor? like this:
class value_to_return {
value_to_return (value_to_return && other) {
// how to write it here? I think std::move is supposed to be used?
}
}
THanks !!!
THanks!!!
推荐答案
Modem C ++编译器将实现:给定类型 T
:
Modem C++ compiler will implement: given a type T
:
- 如果T有一个可访问的复制或移动构造函数,编译器可能会
选择删除复制。这是所谓的(命名的)返回值
优化(RVO),它甚至在C之前指定 - 否则,如果T有一个移动构造函数,T已移动(自C ++ 11 )。
- 否则,如果T有复制构造函数,则会复制T。
- 否则会产生编译时错误。
- If T has an accessible copy or move constructor, the compiler may choose to elide the copy. This is the so-called (named) return value optimization (RVO), which was specified even before C++11 and is supported by most compilers.
- Otherwise, if T has a move constructor, T is moved(Since C++11).
- Otherwise, if T has a copy constructor, T is copied.
- Otherwise, a compile-time error is emitted.
这篇关于如何避免复制时我回来的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!