gpt4 book ai didi

c++ - 将参数作为 const & 或 && 传递

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:25:58 25 4
gpt4 key购买 nike

考虑以下内容,其中一些内容通过多层添加到 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));

并获得最少数量的拷贝。

有没有一种方法可以在不重复附加代码并且不创建 Add 函数模板函数的情况下实现这一点?

最佳答案

为右值和左值重载两个方法是一种方法:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com