我是 C++ 初学者,但不是编程初学者。
我正在尝试学习 C++(c++11),但对我来说最重要的事情还不清楚:传递参数。
我考虑了这些简单的例子:
CreditCard(std::string number, int expMonth, int expYear,int pin):number(number), expMonth(expMonth), expYear(expYear), pin(pin)
Account(std::string number, float amount, CreditCard creditCard) : number(number), amount(amount), creditCard(creditCard)
Client(std::string firstName, std::string lastName, std::vector<Account> accounts):firstName(firstName), lastName(lastName), accounts(accounts)
当我创建一个帐户时,我这样做:
CreditCard cc("12345",2,2015,1001);
Account acc("asdasd",345, cc);
显然,在这种情况下信用卡将被复制两次。
如果我将该构造函数重写为
Account(std::string number, float amount, CreditCard& creditCard)
: number(number)
, amount(amount)
, creditCard(creditCard)
会有一份。
如果我将其重写为
Account(std::string number, float amount, CreditCard&& creditCard)
: number(number)
, amount(amount)
, creditCard(std::forward<CreditCard>(creditCard))
将有2个移动,没有拷贝。
我认为有时您可能想要复制一些参数,有时您不想在创建该对象时复制。
我来自 C#,习惯于引用,这对我来说有点奇怪,我认为每个参数应该有 2 个重载,但我知道我错了。
有没有关于如何在 C++ 中发送参数的最佳实践,因为我真的发现它,让我们说,不是微不足道的。你会如何处理我上面提到的例子?
最佳答案
首先是最重要的问题:
Are there any best practices of how to send parameters in C++ because I really find it, let's say, not trivial
如果您的函数需要修改 传递的原始对象,以便在调用返回后,调用者可以看到对该对象的修改,然后您应该传递 左值引用 :
void foo(my_class& obj)
{
// Modify obj here...
}
如果您的函数 不需要修改原对象,也不需要创建拷贝 (换句话说,它只需要观察它的状态),那么你应该通过 左值引用
const
:void foo(my_class const& obj)
{
// Observe obj here
}
这将允许您使用左值(左值是具有稳定标识的对象)和右值(例如,右值是临时对象或您将要移动的对象作为调用
std::move()
的结果)调用该函数。人们也可能会争辩说 用于基本类型或复制速度快的类型 ,例如
int
, bool
, 或 char
,如果函数只需要观察值就不需要传引用,通过值(value)传递应该受到青睐 .如果不需要引用语义,那是正确的,但是如果函数想要在某处存储指向同一个输入对象的指针,以便将来读取该指针将看到在其他部分执行的值修改呢?代码?在这种情况下,通过引用传递是正确的解决方案。如果您的函数 不需要修改原始对象,但需要存储该对象的拷贝 (可能在不改变输入的情况下返回输入转换的结果),那么你可以考虑 按值(value)取 :
void foo(my_class obj) // One copy or one move here, but not working on
// the original object...
{
// Working on obj...
// Possibly move from obj if the result has to be stored somewhere...
}
调用上述函数在传递左值时总是会产生一份拷贝,而在传递右值时总是会产生一次移动。如果您的函数需要将此对象存储在某处,您可以从它执行额外的移动(例如,在
foo()
是 a member function that needs to store the value in a data member 的情况下)。万一搬家很贵对于
my_class
类型的对象,那么你可以考虑重载 foo()
并为左值提供一个版本(接受对 const
的左值引用)和一个用于右值的版本(接受一个右值引用):// Overload for lvalues
void foo(my_class const& obj) // No copy, no move (just reference binding)
{
my_class copyOfObj = obj; // Copy!
// Working on copyOfObj...
}
// Overload for rvalues
void foo(my_class&& obj) // No copy, no move (just reference binding)
{
my_class copyOfObj = std::move(obj); // Move!
// Notice, that invoking std::move() is
// necessary here, because obj is an
// *lvalue*, even though its type is
// "rvalue reference to my_class".
// Working on copyOfObj...
}
上面的函数非常相似,事实上,你可以用它来制作一个函数:
foo()
可以成为一个函数模板,你可以使用 完美转发用于确定传递的对象的移动或拷贝是否将在内部生成:template<typename C>
void foo(C&& obj) // No copy, no move (just reference binding)
// ^^^
// Beware, this is not always an rvalue reference! This will "magically"
// resolve into my_class& if an lvalue is passed, and my_class&& if an
// rvalue is passed
{
my_class copyOfObj = std::forward<C>(obj); // Copy if lvalue, move if rvalue
// Working on copyOfObj...
}
您可能想通过观看 this talk by Scott Meyers 了解有关此设计的更多信息(请注意他使用的术语“通用引用文献”是非标准的)。
要记住的一件事是
std::forward
通常最终会移动到右值,所以即使它看起来相对无害,多次转发同一个对象可能会带来麻烦——例如,从同一个对象移动两次!所以小心不要把它放在循环中,也不要在函数调用中多次转发相同的参数:template<typename C>
void foo(C&& obj)
{
bar(std::forward<C>(obj), std::forward<C>(obj)); // Dangerous!
}
另请注意,除非您有充分的理由,否则您通常不会求助于基于模板的解决方案,因为它会使您的代码更难阅读。 通常,您应该专注于清晰和简单 .
以上只是简单的指导方针,但在大多数情况下,它们会为您指明良好的设计决策。
关于您帖子的其余部分:
If i rewrite it as [...] there will be 2 moves and no copy.
这是不正确的。首先,右值引用不能绑定(bind)到左值,所以这只会在您传递类型为
CreditCard
的右值时编译。给你的构造函数。例如:// Here you are passing a temporary (OK! temporaries are rvalues)
Account acc("asdasd",345, CreditCard("12345",2,2015,1001));
CreditCard cc("12345",2,2015,1001);
// Here you are passing the result of std::move (OK! that's also an rvalue)
Account acc("asdasd",345, std::move(cc));
但是,如果您尝试这样做,它将无法正常工作:
CreditCard cc("12345",2,2015,1001);
Account acc("asdasd",345, cc); // ERROR! cc is an lvalue
因为
cc
是左值,右值引用不能绑定(bind)到左值。此外,将引用绑定(bind)到对象时,不执行任何移动 : 这只是一个引用绑定(bind)。因此,只会有一个 Action 。因此,根据本答案第一部分中提供的指导方针,如果您担心采取
CreditCard
时产生的移动次数。按值,您可以定义两个构造函数重载,一个采用对 const
的左值引用。 ( CreditCard const&
) 和一个采用右值引用 ( CreditCard&&
)。重载解析会在传递左值时选择前者(在这种情况下,将执行一次复制),而在传递右值时(在这种情况下,将执行一次移动)时选择后者。
Account(std::string number, float amount, CreditCard const& creditCard)
: number(number), amount(amount), creditCard(creditCard) // copy here
{ }
Account(std::string number, float amount, CreditCard&& creditCard)
: number(number), amount(amount), creditCard(std::move(creditCard)) // move here
{ }
您对
std::forward<>
的使用当您想要实现完美转发时通常会看到。在这种情况下,您的构造函数实际上是一个构造函数模板,看起来或多或少如下template<typename C>
Account(std::string number, float amount, C&& creditCard)
: number(number), amount(amount), creditCard(std::forward<C>(creditCard)) { }
从某种意义上说,这将我之前展示的两个重载合并为一个函数:
C
将被推导出为 CreditCard&
如果您正在传递一个左值,并且由于引用折叠规则,它将导致此函数被实例化:Account(std::string number, float amount, CreditCard& creditCard) :
number(num), amount(amount), creditCard(std::forward<CreditCard&>(creditCard))
{ }
这将导致
creditCard
的复制构造,如您所愿。另一方面,当传递右值时,C
将被推导出为 CreditCard
, 而这个函数将被实例化:Account(std::string number, float amount, CreditCard&& creditCard) :
number(num), amount(amount), creditCard(std::forward<CreditCard>(creditCard))
{ }
这将导致
creditCard
的移动构造,这就是您想要的(因为传递的值是一个右值,这意味着我们有权从中移动)。
关于c++ - 如何正确传递参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15600499/