当前位置:网站首页>Tips for this week 131: special member functions and ` = Default`
Tips for this week 131: special member functions and ` = Default`
2022-07-07 17:57:00 【-Flying crane-】
As totw#131 Originally published in 2017 year 3 month 24 Japan
from James Dennett ([email protected]) A literary creation
from the beginning ,C++ It supports the compiler declaration version of some so-called special member functions : Default constructor 、 Destructor 、 Copy constructor and copy assignment operator . C++11 Added move construction and move assignment to the list , And added syntax (=default and =delete) To control when these default values are declared and defined .
=default What's the role , Why do we use it ?
Write =default We tell the compiler “ What you usually do for this special member function ” The way . Why should we do this instead of writing the implementation manually or having the compiler declare one for us ?
- We can change the access level ( for example , Make constructors protected rather than public ), Make the destructor virtual , Or restore the function that will be suppressed ( for example , Default constructor for classes with other user declared constructors ) And still Let the compiler generate functions for us .
- If you copy / Moving members is enough , Compiler defined copy and move operations do not need to be maintained every time members are added or deleted .
- The special member functions provided by the compiler can be unimportant ( When all the operations they call on themselves are unimportant ), This can make them faster 、 More secure .
- Types with default constructors can be aggregated , Therefore, aggregation initialization is supported , Types with user supplied constructors cannot .
- Explicitly declaring a default member provides us with a place , Used to record the semantics of the result function .
- In class templates ,=default It's a simple way , To conditionally declare operations , It depends on whether some basic types provide it .
When we use =default when , The compiler will check whether it can synthesize inline definitions for this function . If possible , It just goes on . If not , This function is actually declared deleted , Like we wrote =delete equally . This is exactly what we need to transparently wrap classes ( for example , If we are defining a class template ), But readers may be surprised .
If the initial declaration of the function uses =default, Or if the compiler declares a special member function that is not declared by the user , Will derive the appropriate noexcept standard , This may allow faster code .
How does it work ?
stay C++11 Before , If we need a default constructor or have other constructors , So we can write like this :
class A {
public:
A() {
} // User-provided, non-trivial constructor makes A a non-aggregate.
};
from C++11 At first we have more choices :
class C {
public:
C() = default; // misleading: C has a deleted default constructor
private:
const int i; // const => must always be initialized.
};
class D {
public:
D() = default; // unsurprising, but not explicit: D has a default constructor
private:
std::unique_ptr<int> p; // std::unique_ptr has a default constructor
};
obviously , We should not write classes C Code like that : In non template , Only if you want this class to support this operation ( Then test whether it supports ) Use only when =default. clang-tidy Including the inspection of this .
After the first declaration of a special member function ( That is, outside the class ) Use =default when , It has a simpler meaning : It tells the compiler to define functions , And give an error when it is impossible to do so . When used outside the class =default when , The default function will not be trivial : Trivial is determined by the first statement ( So all clients agree whether the operation is trivial ).
If you don't need your class to be an aggregate and you don't need a constructor, it's trivial , Then the default constructor outside the class definition , Consider the following example E and F, It's usually a good choice . Its meaning is clear to readers , And checked by the compiler . For special cases of default constructors or destructors , We can write {} instead of =default, But for other default operations , Compiler generated implementations are not so simple , For consistency , It is best to write in all applicable cases =default.
class E {
public:
E(); // promises to have a default constructor, but...
private:
const int i; // const => must always be initialized.
};
inline E::E() = default; // compilation error here: would not initialize `i`
class F {
public:
F(); // promises to have a default constructor
private:
std::unique_ptr<int> p; // std::unique_ptr has a default constructor
};
inline F::F() = default; // works as expected
Suggest
first =default Instead of writing an equivalent implementation manually , Even if the implementation is just {}. Optionally , Omit from the initial declaration =default And provide a separate default implementation .
Note the default move operation . Objects from mobile still have to satisfy the invariants of their types , And the default implementation usually does not preserve the relationship between fields .
Outside the template , If =default No implementation provided , Use the =delete.
边栏推荐
- YARN Capacity Scheduler容量调度器(超详细解读)
- toast会在程序界面上显示一个简单的提示信息
- Audio Device Strategy 音频设备输出、输入 选择 基于7.0 代码
- List selection JS effect with animation
- DatePickerDialog和trimepickerDialog
- 2021年全国平均工资出炉,你达标了吗?
- Understanding of 12 methods of enterprise management
- Interviewer: why is the page too laggy and how to solve it? [test interview question sharing]
- Functions and usage of ratingbar
- 线上比赛相关规则补充说明
猜你喜欢
In depth understanding of USB communication protocol
Please insert the disk into "U disk (H)" & unable to access the disk structure is damaged and cannot be read
第3章业务功能开发(实现记住账号密码)
Toast will display a simple prompt message on the program interface
Deep learning - make your own dataset
【可信计算】第十二次课:TPM授权与会话
Functions and usage of imageswitch
测试3个月,成功入职 “字节”,我的面试心得总结
Interviewer: why is the page too laggy and how to solve it? [test interview question sharing]
Mobile pixel bird game JS play code
随机推荐
TabHOST 选项卡的功能和用法
Run Yolo v5-5.0 and report an error. If the sppf error cannot be found, solve it
Show progress bar above window
做软件测试 掌握哪些技术才能算作 “ 测试高手 ”?
深入浅出图解CNN-卷积神经网络
手机app外卖订餐个人中心页面
【重新理解通信模型】Reactor 模式在 Redis 和 Kafka 中的应用
Click on the top of today's headline app to navigate in the middle
Functions and usage of viewflipper
[tpm2.0 principle and Application guide] Chapter 1-3
本周小贴士#141:注意隐式转换到bool
textSwitch文本切换器的功能和用法
第3章业务功能开发(安全退出)
Automated testing: a practical skill that everyone wants to know about robot framework
Notification is the notification displayed in the status bar of the phone
Simple loading animation
swiper左右切换滑块插件
Import requirements in batches during Yolo training Txt
Based on pytorch, we use CNN to classify our own data sets
Robot engineering lifelong learning and work plan-2022-