gpt4 book ai didi

c++ - 使用初始化列表中的引用初始化对象成员

转载 作者:行者123 更新时间:2023-11-30 02:06:21 25 4
gpt4 key购买 nike

我这样做对吗?这是我的代码的高度简化版本:

class Logger {
public:
Logger(std::ostream) { /*...*/}
};

class Driver {
public:
Driver() : m_logger(std::cout) {}
Driver(Logger& logger) : m_logger(logger) {}
private
Logger m_logger;
};

所以我的类 Driver 有一个类型为 Logger 的成员。当我调用无参数构造函数 Driver() 时,Driver 实例使用 std::创建了它自己的 Logger 实例: cout.

调用 Driver(Logger) 时,该实例应使用已存在的 Logger 实例作为引用传递。

以上代码使用 g++ 编译。虽然我了解调用 Driver() 时会发生什么,但我不明白调用 Driver(Logger) 时会发生什么。 Logger 没有接受对 Logger 的引用作为参数的构造函数(“复制构造函数”)。那么调用Driver(Logger)时执行了什么?

最佳答案

Logger 的普通复制构造函数已为您合成,除非您自己声明一个。

这与为您合成普通默认构造函数的方式非常相似(如果您不声明默认用户定义的构造函数)。


[C++11: 12.8/7]: If the class definition does not explicitly declare a copy constructor, one is declared implicitly. If the class definition declares a move constructor or move assignment operator, the implicitly declared copy constructor is defined as deleted; otherwise, it is defined as defaulted (8.4). The latter case is deprecated if the class has a user-declared copy assignment operator or a user-declared destructor. Thus, for the class definition

struct X {
X(const X&, int);
};

a copy constructor is implicitly-declared. If the user-declared constructor is later defined as

X::X(const X& x, int i =0) { /* ... */ }

then any use of X’s copy constructor is ill-formed because of the ambiguity; no diagnostic is required.

[C++11: 12.8/8]: The implicitly-declared copy constructor for a class X will have the form

X::X(const X&)

if

  • each direct or virtual base class B of X has a copy constructor whose first parameter is of type const B& or const volatile B&, and
  • for all the non-static data members of X that are of a class type M (or array thereof), each such class type has a copy constructor whose first parameter is of type const M& or const volatile M&.

Otherwise, the implicitly-declared copy constructor will have the form

X::X(X&)

关于c++ - 使用初始化列表中的引用初始化对象成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8849568/

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