拷贝初始化限制:其实只要都加上explicit来强制显示调用,就可以不用管拷贝初始化或者直接初始化了; 编译器可以绕过拷贝构造函数:在拷贝初始化过程中,编译器可以略过(但不是必须)拷贝/移动构造函数,直接创建对象 C/C++:编译器将把 std::string str="123sadw2-asd"; 改成这样 std::string str("123sadw2-asd")...
explicit operator bool() 比运算符 unspecified-bool-type() 更严格。 explicit operator bool() 允许到 bool 的显式转换 - 例如,在给定 shared_ptr<X> sp 的情况下,bool b(sp) 和static_cast<bool>(sp) 都有效 - 允许对 bool 进行布尔值可测试的“上下文转换”- 例如,if (sp)、!sp、sp && 等。
// spec1_explicit.cpp // compile with: /EHsc #include <stdio.h> class C { public: int i; explicit C(const C&) // an explicit copy constructor { printf_s("\nin the copy constructor"); } explicit C(int i ) // an explicit constructor { printf_s("\nin the constructor"); } C...
destructor:析构函数 constructor:构造函数 copy constructor:拷贝构造函数 move constructor:移动构造函数 delegating constructor:代理构造函数 delegation cycle: 委派环 shollw copy:浅拷贝 deep copy:深拷贝 Move semantics:移动语义 xvalue,eXpiring Value:将亡值 prvlaue,Pure Rvalue:纯右值 Pass by value: 按值传...
CheckXCoordinate(20.0, 20.0);当然这会削弱API的类型安全性,因为现在编译器不会将第一个参数的类型强制为显式向量对象。结果,客户端有可能忘记正确的参数顺序并以错误的顺序传递它们。如何解决这个问题?这就是为什么除非你知道要支持隐式转换,否则应始终对任何单参数构造函数使用explicit关键字。class...
explicit Message(const std::string &str = ""): contents(str) { } // copy control to manage pointers to this Message Message(const Message&); // copy constructor Message& operator=(const Message&); // copy assignment ~Message(); // destructor ...
ifstream file2 = "filename"; // error:copy constructor is private Sales_item item = string("3333"); //this initilization is ok only if the Sales_item(const string&) constructor is not explicit 1.1构造函数与数组元素 #include<iostream>usingnamespacestd;classA ...
// C2280_explicit.cpp// compile with: cl /c /W4 C2280_explicit.cppstructA{A(); A(int) =delete; };structB{A a1; A a2 = A(3);// C2280, calls deleted A::A(int)// To fix, remove the call to A(int)};voidf(){
通常直接初始化和复制初始化仅在低级别优化上存在差异,然而,对于不支持复制的类型,或者使用非explicit构造函数的时候,它们有本质区别: ifstream file1("filename")://ok:direct initialization ifstream file2 = "filename";//error:copy constructor is private ...
答案是肯定的。但是在工程应用中一般不用类型转换函数,因为无法抑制隐式的调用类型转换函数(类型转换构造函数可以通过explicit来抑制其被隐式的调用),而隐式调用经常是bug的来源。实际工程中替代的方式是定义一个普通函数,通过显式的调用来达到类型转换的目的。