gpt4 book ai didi

c++ - c++11 中首选的初始化方式

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:14:09 25 4
gpt4 key购买 nike

<分区>

int i = 0; // (a) Old C style should I use it?
int i{0}; // (b) Brace direct init
int i{}; // (c) Same as (b)
int i = {0}; // (d) as (b)
int i = {}; // (e) as (c)
auto i = 0; // (f) auto = int in this case.
auto i = int{0}; // (g) auto = more specific.
auto i = int{}; // (h) same as above (g)

使用哪一个?萨特说使用:

int i = 0;
auto i = 0;

为什么不呢:

int i = {0};
auto i = int{0};

在某些情况下我应该去掉“=”吗:

int i{0};
auto i{0}; // i is not what some might expect in this case. So I would prefer using "=" everywhere possible like int i = {0}; ...

编辑:这就是我的目标,在我看来这是最一致的:

rectangle       w   = { origin(), extents() }; 
complex<double> c = { 2.71828, 3.14159 };
mystruct m = { 1, 2 };
int a[] = { 1, 2, 3, 4 };
vector<int> v = { 1, 2, 3, 4 };
point p = {}; // Default initializes members
int i = {0}; // Checked assembly for this and it's binary the same as int i{0}; could be written also as int i = {};
string s = {""}; // Same as string s = {}; (OR) string s;

现实生活中的例子:

std::string       title              = { pt.get<std::string>("document.window.title") };
const std::string file = { R"(CoreSettings.xml)" };
int_least64_t currentTick = { 0 }; // (OR) int_least64_t currentTick = {};
bool isRunning = { false }; // (OR) bool isRunning = {};
App* app = { nullptr }; // (OR) App* app = {};
Event event = {};
double detectedFrameRate = { 1000000000.0 / (swapIntervalDeltaCumulative / 20.0) };
double precision = { static_cast<double>(boost::chrono::high_resolution_clock::period::num)
/ boost::chrono::high_resolution_clock::period::den };
auto timeSpan = boost::chrono::duration_cast<boost::chrono::nanoseconds>(nowTime - startTime);

替代方案是:

std::string       title             { pt.get<std::string>("document.window.title") };
const std::string file { R"(CoreSettings.xml)" };
int_least64_t currentTick { 0 }; // (OR) int_least64_t currentTick{};
bool isRunning { false }; // (OR) bool isRunning{};
App* app { nullptr }; // (OR) App* app{};
Event event {};
double detectedFrameRate { 1000000000.0 / (swapIntervalDeltaCumulative / 20.0) };
double precision { static_cast<double>(boost::chrono::high_resolution_clock::period::num)
/ boost::chrono::high_resolution_clock::period::den };
auto timeSpan = boost::chrono::duration_cast<boost::chrono::nanoseconds>(nowTime - startTime);

如果不使用大括号,它会很难看或容易出错:

int_least64_t     currentTick        = 0; // C style - changed this from double to int recently and compiler did not complain so I had something like int_least64_t currentTick = 0.0; ugly!
bool isRunning = false; // C style
App* app = nullptr; // C mixed with C++11 style;
Event event; // might not be initialized by all compilers
int someInt = func(); // func() returns double no error but narrowing.

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