繁体   English   中英

需要澄清复制构造函数

[英]Need clarification on copy constructor

从下面给出的代码片段的角度来看,我有一个关于何时调用 C++ 中的复制构造函数的问题:

bool do_stuff(int a, int b, char *c, Uid key = 0);

这里的keydo_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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM