考虑以下情况,其中一些内容通过多个层添加到 vector 中:
class A {
public:
void Add(Content c) {
// Considerable amount of checking code here.
v.push_back(c);
}
private:
std::vector<Content> v;
};
class B {
public:
void Add(Content c) {
// Considerable amount of additional code here.
a.Add(c);
}
private:
A a;
};
class C {
public:
void Add(Content c) {
// Considerable amount of additional code here.
b.Add(c);
}
private:
B b;
};
这可以继续,但你明白这里的重点了。我希望通过复制或移动添加内容,即通过 Push_back(const Content&) 或 Push_back(Content&&)。调用者应该能够调用:
C c;
Content z;
c.Add(z);
或
c.Add(move(z));
并获得最少数量的拷贝。
是否有一种方法可以实现此目的,而无需重复附加代码且无需创建“添加函数”模板函数?
最佳答案
重载右值和左值的两个方法是一种方法:
void Add(const Content & c);
void Add(Content && c);
使用完美转发您可以避免两次过载。您应该将所有 add
方法设置为如下所示:
template<typename T>
void add(T&& a)
{
b.Add(std::forward<T>(a));
}
另一种更好的方法(IMO)是使Content
可移动。如果 Content
是真正的类(不是模板的占位符),您可以这样做:
class Content
{
public:
Content(const Content &);
Content(Content &&);
Content &operator=(Content); // Copy and swap idiom!
~Content();
};
之后您可以重写Add
方法,如下所示:
void Add(Content c) {
b.Add(std::move(c));
^^^^^^^^^^^^
}
这种方法的优点是,您可以从调用方透明地移动或复制。
关于c++ - 将参数作为 const & 或 && 传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19336161/