作者poyenc (发箍)
看板C_and_CPP
标题Re: [问题] C++初始化为何常使用单冒号?
时间Wed Nov 25 05:11:00 2020
※ 引述《d630200x (DOGE)》之铭言:
: 有看到有人说这样效率比较好
: 但我自己测试来看是看不出差异(可能是我测试方式太简单)
: 就我个人来说我是觉得写在函式里较为美观
: 但是很多网路上的无论是simple code还是教学,在初始化时是比较常看到单冒号的
: 请问是真的效率上差很多,还是单纯风格差异而已?
: -----
: Sent from JPTT on my Asus ASUS_I01WD.
这在
语法还有
语意上有不同的考量, 後面会举两个例子说明.
语法
通常初学者会有这个问题是因为使用到
SemiRegular 型别物件作为资料成员
, 如
int,
double 等等 vocabulary type, 它们都有功能相仿的建构子
(constructor) 及
operator=() 可呼叫. 不妨写个类别实验看看两种写法有
什麽差异:
#include <cstdio>
struct MyInt {
MyInt() { puts(
__PRETTY_FUNCTION__); }
MyInt(
int) { puts(
__PRETTY_FUNCTION__); }
MyInt&
operator=(
int) {
puts(
__PRETTY_FUNCTION__);
return *
this;
}
};
struct Test {
Test() { i =
0; }
Test(
bool) : i(
0) {}
MyInt i;
};
Test();
// print: MyInt::MyInt()
// MyInt& MyInt::operator=(int)
Test(
true);
// print: MyInt::MyInt(int)
建构子是绝对会被呼叫的函式, 因此物件的状态若能在建构子里面准备好, 就
不需要额外呼叫别的函式做重复的事情.
语意
资料成员/父类别也算是物件的一部分, 在它们的建构子都成功结束的前提下
, 我们才有办法建构出完整的物件. 所以语言设计上你无法消除从资料成员/
父类别建构子丢出的例外:
#include <iostream>
#include <stdexcept>
struct Foo {
Foo() {
throw std::runtime_error(
"message"); }
};
struct Bar {
Bar()
try {
// constructor body
}
catch (std::exception& e) {
std::cerr << e.what() << std::endl;
// exception will be re-thrown here
}
Foo foo;
};
对 std::vector 这类会在获取记忆体失败时丢出例外的资料成员, 我们可以
用 two-phase initialization 来
延後准备物件状态, 让物件有机会完成初始
化 (虽然通常呼叫建构子比较合理):
#include <vector>
struct Example {
Example() {
do {
try {
v.resize(
10'000'000);
}
catch (std::bad_alloc& e) {
// do something here
}
}
while (empty(v));
// retry until success
}
std::vector<
int> v;
};
所以风格怎样的倒不是重点, 重要的是你要知道自己在做什麽 :)
--
[P1389R1] Standing Document for SG20: Guidelines for Teaching
C++ to Beginners
https://wg21.link/p1389r1
SG20 Education and Recommended Videos for Teaching C++
https://www.cjdb.com.au/sg20-and-videos
--
※ 发信站: 批踢踢实业坊(ptt.cc), 来自: 123.193.76.216 (台湾)
※ 文章网址: https://webptt.com/cn.aspx?n=bbs/C_and_CPP/M.1606252263.A.77F.html
1F:推 petercoin: 推一个 11/25 11:31
※ 编辑: poyenc (123.193.76.216 台湾), 11/25/2020 11:38:46
2F:推 s4300026: 推 11/25 17:41
3F:推 KevinR: m 11/25 19:07
4F:推 F04E: 推 11/26 10:17
5F:推 deangood01: 有开优化 compiler应该还是会帮忙做 09/14 17:36