zoukankan      html  css  js  c++  java
  • C++ essentials 之 explicit constructor

    这篇博客的源起是下面的一段代码

    #include <bits/stdc++.h>
    using namespace std;
    
    int main(){
        priority_queue<long long> que;
        // some operations on que
        que = {};
        // some operations on que
        return 0;
    }
    

    其中 que = {} 相当于 que.clear();std::priority_queue 并没有 clear() 方法)。以前我清空 priority_queue 用的是

    while(!que.empty()){
        que.pop();
    }
    

    然而编译器对这个语句给出了一个警告:
    (g++ 6.3.0:g++ -Wall -std=c++14

    In function 'int main()':
    7:12: warning: converting to 'std::priority_queue<long long int>' from initializer list would use explicit constructor 'std::priority_queue<_Tp, _Sequence, _Compare>::priority_queue(const _Compare&, _Sequence&&) [with _Tp = long long int; _Sequence = std::vector<long long int, std::allocator<long long int> >; _Compare = std::less<long long int>]'
        que = {};
               ^
    7:12: note: in C++11 and above a default constructor can be explicit
    

    概念

    implicit class-type conversion

    Every constructor that can be called with a single argument defines an implicit conversion to a class type. Such constructors are sometimes referred to as conversion constructors.

    explicit constructors

    We can prevent the use of a constructor in a context that requires an implicit conversion by declaring the constructor as explicit.

    The explicit keyword is meaningful only on constructors that can be called with a single argument. Constructors that require more arguments are not used to perform a conversion, so there is no need to designate such constructors as explicit. The explicit keyword is used only on the constructor declaration inside the class. It is not repeated on a definition made outside the class body.

    One context in which implicit conversions happen is when we use the copy form of initialization (with an =). An explicit constructor cannot be used with the copy form of initialization; it can be used only with the direct form of initialization. Moreover, the compiler will not use this constructor in an automatic conversion.

  • 相关阅读:
    学习笔记8:《大型网站技术架构 核心原理与案例分析》之 固若金汤:网站的安全架构
    学习笔记8:《大型网站技术架构 核心原理与案例分析》之 随需应变:网站的可扩展架构
    13 集合
    12 泛型程序设计
    11 异常, 日志, 断言和调试
    10 部署应用程序和applet
    08 事件处理
    06 接口与内部类
    05 继承
    04 对象与类
  • 原文地址:https://www.cnblogs.com/Patt/p/9345720.html
Copyright © 2011-2022 走看看