为了支持移动语义,函数参数应该由unique_ptr,按值还是按rvalue接受? [英] To support move semantics, should function parameters be taken by unique_ptr, by value, or by rvalue?
问题描述
我的函数之一将向量作为参数并将其存储为成员变量.我正在使用const引用向量,如下所述.
One of my function takes a vector as a parameter and stores it as a member variable. I am using const reference to a vector as described below.
class Test {
public:
void someFunction(const std::vector<string>& items) {
m_items = items;
}
private:
std::vector<string> m_items;
};
但是,有时items
包含大量字符串,因此我想添加一个支持移动语义的函数(或用新函数替换该函数).
However, sometimes items
contains a large number of strings, so I'd like to add a function (or replace the function with a new one) that supports move semantics.
我正在考虑几种方法,但是我不确定该选择哪种方法.
I am thinking of several approaches, but I'm not sure which one to choose.
1)unique_ptr
1) unique_ptr
void someFunction(std::unique_ptr<std::vector<string>> items) {
// Also, make `m_itmes` std::unique_ptr<std::vector<string>>
m_items = std::move(items);
}
2)按值传递并移动
void someFunction(std::vector<string> items) {
m_items = std::move(items);
}
3)右值
void someFunction(std::vector<string>&& items) {
m_items = std::move(items);
}
我应该避免使用哪种方法,为什么?
Which approach should I avoid and why?
推荐答案
除非您有理由让vector驻留在堆中,否则我建议不要使用unique_ptr
Unless you have a reason for the vector to live on the heap, I would advise against using unique_ptr
向量的内部存储无论如何都驻留在堆上,因此,如果使用unique_ptr
,则将需要2个间接度,一个将引用该向量的指针取消引用,然后再次解引用内部存储缓冲区.
The vector's internal storage lives on the heap anyway, so you'll be requiring 2 degrees of indirection if you use unique_ptr
, one to dereference the pointer to the vector, and again to dereference the internal storage buffer.
因此,我建议使用2或3.
As such, I would advise to use either 2 or 3.
如果使用选项3(需要右值引用),则在调用
If you go with option 3 (requiring an rvalue reference), you are foisting a requirement on the users of your class that they pass an rvalue (either directly from a temporary, or move from an lvalue), when calling someFunction
.
从左值移出的要求很繁琐.
The requirement of moving from an lvalue is onerous.
如果您的用户想要保留矢量的副本,则必须跳过这一步.
If your users want to keep a copy of the vector, they have to jump through hoops to do so.
std::vector<string> items = { "1", "2", "3" };
Test t;
std::vector<string> copy = items; // have to copy first
t.someFunction(std::move(items));
但是,如果您选择选项2,则用户可以决定是否要保留副本-选择权是他们的
However, if you go with option 2, the user can decide if they want to keep a copy, or not - the choice is theirs
保留副本:
std::vector<string> items = { "1", "2", "3" };
Test t;
t.someFunction(items); // pass items directly - we keep a copy
请勿保留副本:
std::vector<string> items = { "1", "2", "3" };
Test t;
t.someFunction(std::move(items)); // move items - we don't keep a copy
这篇关于为了支持移动语义,函数参数应该由unique_ptr,按值还是按rvalue接受?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!