可以"T t = {};"和"T t {};"产生不同的结果? [英] Can "T t = {};" and "T t{};" produce different results?

查看:102
本文介绍了可以"T t = {};"和"T t {};"产生不同的结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题很简单.是否可以构造这样的T类型,对于它来说以下两个变量声明将产生不同的结果?

The question is simple. Is it possible to construct such a type T, for which the following two variables declarations will produce different results?

T t1 = {};
T t2{};

我已经研究了cppreference和标准一个多小时了,我了解以下内容:

I've been digging through the cppreference and the standard for more than an hour now, and I understood the following:

  • T t2{}; is a value initialization. No surprises here.
  • T t1 = {} is a list initialization with an empty braced-init-list.

但是最后一个是棘手的,因为列表初始化的效果"是令人印象深刻的...列表.对于类,基本类型和集合,似乎可以归结为值初始化.但是我不确定我是否没有错过任何事情.

But the last one is tricky since the "effects of list initialization" is an impressive... list. Which for classes, fundamental types and aggregates seems to boil down to value initialization. But I am not sure I haven't missed anything.

也许您可以提供一个上下文,两个声明在其中会产生不同的影响?

Maybe you can provide a context, in which the two declarations will have different effects?

UPD:关于explicit构造函数的出色答案!下一阶段:是否可以同时执行两个语句,但是它们对编译/运行时的影响不同?

UPD: Excellent answers about explicit constructors! Next level: is it possible that both statements compile, but have different effects on compile/run time?

推荐答案

如果您考虑一种情况,其中一个语句将会编译,而另一个语句不会编译为不同的效果",然后是的,这是一个上下文:

If you consider a case in which one statement will compile, but the other will not compile as "different effects," then yes, here's a context:

#include <iostream>

class T {
public:
    int data{ 0 };
    explicit T() {
        data = 0;
        std::cout << "Default constructor" << std::endl;
    }
};

int main()
{
    T t1 = {};
    T t2{};
    return 0;
}

使用clang-cl声明/初始化t1的行给出了以下内容:

The line declaring/initializing t1 gives the following, with clang-cl:

错误:所选的构造函数在复制初始化中是显式的

error : chosen constructor is explicit in copy-initialization

MSVC编译器还抱怨:

错误C2512:'T':没有适当的默认构造函数可用
消息:类"T"的构造函数被声明为显式"

error C2512: 'T': no appropriate default constructor available
message : Constructor for class 'T' is declared 'explicit'

这篇关于可以"T t = {};"和"T t {};"产生不同的结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆