谈谈explicit关键字
- 作者:xiaoxiao
- 发表时间:2020-12-23 10:59
- 来源:未知
今天看到公司的代码内有大量的explicit关键字,但是老版的MSDN内例子并不完善,实在是不明白,最终从网上一篇文章内找到了答案:原来explicit是为了防止隐式使用拷贝构造函数的.以下附上从新版MSDN中找到的例子和网上那篇文章:
// Copy From MSDN
This keyword is a declaration specifier that can only be applied to in-class constructor declarations. An explicit constructor cannot take part in implicit conversions. It can only be used to explicitly construct an object.
The following program will fail to compile because of the explicit keyword. To resolve the error, remove the explicit keywords and adjust the code in g.
// spec1_explicit.cpp // compile with: /EHsc #include class C { public: int i; explicit C(const C&) // an explicit copy constructor { printf("/nin the copy constructor"); } explicit C(int i ) // an explicit constructor { printf("/nin the constructor"); } C() { i = 0; } }; class C2 { public: int i; explicit C2(int i ) // an explicit constructor { } }; C f(C c) { // C2558 c.i = 2; return c; // first call to copy constructor } void f2(C2) { } void g(int i) { f2(i); // C2558 // try the following line instead // f2(C2(i)); } int main() { C c, d; d = f(c); // c is copied } Note explicit on a constructor with multiple arguments has no effect, since such constructors cannot take part in implicit conversions. However, for the purpose of implicit conversion, explicit will have an effect if a constructor has multiple arguments and all but one of the arguments has a default value.
// Copy From Internet Article
Pointer 不看书不知道自己的C++有多差T_T,看到 explicit 时遇到一个问题。请看下面一段程序: class A{ public: A(int i) : m_i(i){} int m_i; }; int main(){ A a = 0; a = 10; // 这里是什么操作? } 这个操作产生了一个临时对象。 我怀疑是默认赋值运算符 “A &operator = (int i){}”,于是重载了一下该运算符,结果确实运行到重载的运算符函数里了,那么临时对象又是如何产生的呢? 难道默认的赋值运算符是这样操作的? A &operator = (int i){ A a(i); return a; } 这让我想起了类似的函数操作: void fn(A a){ // ... } 这里可以直接写fn(10);也是产生了一个临时对象。 难道真的是这样吗?忘解惑。alexeyomux 老兄你用的是哪个编译器?在我印象之中,好像标准C++并不会给出operator =啊。等我去试一试。
gongminmin 当然会有默认的operator=了 按照c++标准,编译器会生成五个默认成员函数: 默认构造函数 拷贝构造函数 析构函数 operator= operator&