需要澄清复制构造函数
Need clarification on copy constructor
从下面给出的代码片段的角度,我有一个关于C++中的复制构造函数何时被调用的问题:
bool do_stuff(int a, int b, char *c, Uid key = 0);
此处key
是do_stuff()
的默认参数
class Uid {
...
...
private:
u_char data_[UID_LENGTH];
}
现在,Uid
有这些构造函数:
Uid:Uid()
{
memset(data_, 0, UID_LENGTH);
}
/// @brief Copy construct a uid
Uid::Uid(const Uid &id)
{
memcpy(data_, id.data_, UID_LENGTH);
}
/// @brief Copy the contents of ptr as the contents of a new Uid
Uid::Uid(const u_char* ptr)
{
memcpy(data_, ptr, UID_LENGTH);
}
/// @brief Set the contents of a Uid with provided values
Uid::Uid(u_int64_t high, u_int64_t low)
{
…
…
}
当使用三个参数调用 do_stuff
时,将调用 Uid::Uid(const u_char* ptr)
来为 key
创建对象。 Uid::Uid(const u_char* ptr)
是因为没有更好的匹配吗?
将原型更改为...
bool do_stuff(int a, int b, char *c, Uid key = (Uid)0);
...确保 Uid::Uid(const Uid &id)
被调用?
谢谢!
你可能想做
bool do_stuff(int a, int b, char *c, Uid key = Uid{});
这样,如果您使用三个输入参数调用 do_stuff
,将调用默认构造函数。
允许编译器在生成默认 Uid 参数时省略复制构造函数。要查看这一点,请使用 -fno-elide-constructors
重新编译您的程序(假设为 g++)以查看差异。
关于 Uid::Uid(char const*)
构造函数,它 是 最适合 0
因为它仍然可以用作 nullptr
当您当前没有采用标量值的构造函数。
从下面给出的代码片段的角度,我有一个关于C++中的复制构造函数何时被调用的问题:
bool do_stuff(int a, int b, char *c, Uid key = 0);
此处key
是do_stuff()
class Uid {
...
...
private:
u_char data_[UID_LENGTH];
}
现在,Uid
有这些构造函数:
Uid:Uid()
{
memset(data_, 0, UID_LENGTH);
}
/// @brief Copy construct a uid
Uid::Uid(const Uid &id)
{
memcpy(data_, id.data_, UID_LENGTH);
}
/// @brief Copy the contents of ptr as the contents of a new Uid
Uid::Uid(const u_char* ptr)
{
memcpy(data_, ptr, UID_LENGTH);
}
/// @brief Set the contents of a Uid with provided values
Uid::Uid(u_int64_t high, u_int64_t low)
{
…
…
}
当使用三个参数调用 do_stuff
时,将调用 Uid::Uid(const u_char* ptr)
来为 key
创建对象。 Uid::Uid(const u_char* ptr)
是因为没有更好的匹配吗?
将原型更改为...
bool do_stuff(int a, int b, char *c, Uid key = (Uid)0);
...确保 Uid::Uid(const Uid &id)
被调用?
谢谢!
你可能想做
bool do_stuff(int a, int b, char *c, Uid key = Uid{});
这样,如果您使用三个输入参数调用 do_stuff
,将调用默认构造函数。
允许编译器在生成默认 Uid 参数时省略复制构造函数。要查看这一点,请使用 -fno-elide-constructors
重新编译您的程序(假设为 g++)以查看差异。
关于 Uid::Uid(char const*)
构造函数,它 是 最适合 0
因为它仍然可以用作 nullptr
当您当前没有采用标量值的构造函数。