gpt4 book ai didi

C++0x统一初始化 "oddity"

转载 作者:IT老高 更新时间:2023-10-28 22:07:10 26 4
gpt4 key购买 nike

像许多人一样,我对 C++0x 感到非常兴奋.我尝试在新项目中学习和使用新功能,以便编写出最好的、最易于维护的代码。

不用说,我喜欢新初始化器背后的想法。所以我在看它们,这些对我来说很有意义:

T x = { 1, 2, 3 }; // like a struct or native array
T x({1, 2, 3}); // copy construct something like an "object literal" in other languages... cool!
return {1, 2, 3}; // similar to above, but returning it, even cooler!

对我来说没有意义的是:

T x{1, 2, 3};

感觉……很奇怪。我不确定人们想使用什么语法来模仿它,它看起来并不“正确”。

这种语法背后的设计/思想是什么?

似乎它有所作为的唯一例子是这样的:

std::vector<int> the_vec{4};

这会调用初始化列表构造函数,但是为什么不直接写这个呢:

std::vector<int> the_vec = {4};

然后做每个人都已经习惯的事情?

最佳答案

What's the design/thought behind this syntax?

一方面,大括号语法可以避免令人烦恼的解析:

T x(); // function declaration
T x{}; // value-initialized object of type 'T' named 'x'

在 C++03 中,最接近这一点的是 T x((T()));T x = T();,两者都需要 T 具有可访问的复制构造函数。

关于C++0x统一初始化 "oddity",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7031909/

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