-
C++11 delete -
delete解决的问题-
C++编译器 -
c++98 -
c++11 -
隐式转换
-
隐式案例
void cool(int) {} void cool(bool) = delete; int main() { cool(1); cool(false); }[root@localhost test]# g++ -c test.cpp -std=c++98 [root@localhost test]# gcc test.o test.o: In function `main': test.cpp:(.text+0x1d): undefined reference to `cool(bool)' collect2: error: ld returned 1 exit status [root@localhost test]# cat test.cpp void cool(int) {} void cool(bool); int main() { cool(1); cool(false); } [root@localhost test]# vim test.cpp [root@localhost test]# g++ -c test.cpp -std=c++11 test.cpp: In function ‘int main()’: test.cpp:6:15: error: use of deleted function ‘void cool(bool)’ cool(false); ^ test.cpp:2:6: error: declared here void cool(bool) = delete; ^ [root@localhost test]# cat test.cpp void cool(int) {} void cool(bool) = delete; int main() { cool(1); cool(false); }
-
-
差异
-
delete的强大-
强大之处
-
全局函数
deletevoid cool(int) {} void cool(bool) = delete; int main() { cool(1); cool(false); } -
禁止模板实例化
template <typename T> void show(T a) {} template<> void show<bool>(bool) = delete; int main() { show(1); show(false); } -
类成员
class T { public: template <typename T> void show(T a) {} template<> void show<bool>(bool) = delete; }; int main() { T a; a.show(1); a.show(false); } -
C++11标准版class T { public: template <typename T> void show(T a) {} }; template<> void T::show<bool>(bool) = delete; int main() { T a; a.show(1); a.show(false); }
-
-
总结
C++11 delete 更优于私有化声明
最新推荐文章于 2024-08-03 10:03:09 发布
本文探讨了C++11中delete关键字的应用,对比了C++98中使用private未定义方法的问题,并介绍了delete如何在编译阶段阻止错误发生。此外还讨论了delete在普通函数、模板和类成员中的使用。
46

被折叠的 条评论
为什么被折叠?



