gpt4 book ai didi

c++ - T::T(T&)有什么用?

转载 作者:搜寻专家 更新时间:2023-10-31 00:26:24 34 4
gpt4 key购买 nike

为什么有 T::T(T&)T::T(const T&) 更适合 copy

(大概是用来实现move语义的???)

原始描述(被melpomene证明是错误的):

C++11中,支持了一种新形式的复制构造函数T::T(T&)(来自cppreferene/Copy constructor Implicitly declared copy constructor)我想知道它的实际用途是什么?

最佳答案

T(T&) 在 C++11 中并不是新的。新功能是使用 default 关键字来显式定义自动生成的复制构造函数:

T(const T &) = default;

正如您的链接所说:

A class can have multiple copy constructors, e.g. both T::T(const T&) and T::T(T&). If some user-defined copy constructors are present, the user may still force the generation of the implicitly declared copy constructor with the keyword default.

在 C++11 之前,如果你的类中有一个 T(T&) 构造函数,它会阻止 T(const T&) 的自动创建(默认复制构造函数)。从 C++11 开始,您可以同时拥有(用户定义的 T(T&) 构造函数和自动 T(const T&) 构造函数)。


至于非const拷贝构造函数有什么用,答案是“不多”。它确保只能复制可变对象(而不是临时对象),这不是您通常需要的。

(Probably it was used to implement move semantic???)

完全正确。参见例如auto_ptr (现已从 C++ 标准中删除),这类似于我们拥有移动语义之前的 unique_ptr。特别是,它有一个 auto_ptr(auto_ptr &r) constructor这会修改 r(这会导致一些不直观的行为,这就是它从语言中删除的原因)。

关于c++ - T::T(T&)有什么用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52566177/

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