简体   繁体   English

您应该为复制构造函数还是移动构造函数提供默认参数?

[英]Should you provide the copy constructor or the move constructor with a default argument?

Suppose you have the following class:假设您有以下课程:

template<typename T>
class A
{
    ...

    A (T const &t) 
    {
        ...
    }

    A (T &&t) noexcept
    {
        ...
    }
};

Now suppose I want to provide a default argument to one of these (ie, = T{} ).现在假设我想为其中之一提供默认参数(即= T{} )。 Which is more efficient/consistent to default, the copy or the move?哪个比默认、复制或移动更有效/更一致? Does it even matter?这有关系吗? My gut says it doesn't matter performance wise, which leads me to think it would be more consistent to default the copy since you should not bind a temporary to an r-value.我的直觉说这在性能方面无关紧要,这让我认为默认副本会更一致,因为您不应该将临时值绑定到 r 值。

Thoughts?想法?

Those are not copy / move constructors, so you don't have to use a reference at all .这些不是复制/移动构造函数,因此您根本不必使用引用。

Assuming you have distinguished those cases to elide copying t if you can, just have one construtor假设您已经区分了这些情况以尽可能避免复制t ,只需要一个构造函数

template<typename T>
class A
{
    ...

    /* explicit ? */ A (T t = {}) 
    {
        ...
    }
};

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

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