main.cpp: In function ‘int main()’: main.cpp:17:22: error: ‘HomeForSale::HomeForSale(const HomeForSale&)’ is private within this context HomeForSale h3(h2); // compiles and runs without error, which it shouldn't ^ main.cpp:9:5: note: declared private here HomeForSale(const HomeForSale&); ^~~~~~~~~~~ main.cpp:18:10: error: ‘HomeForSale& HomeForSale::operator=(const HomeForSale&)’ is private within this context h2 = h1; // compiles and runs without error, which it shouldn't ^~ main.cpp:10:18: note: declared private here HomeForSale& operator=(const HomeForSale&);
这种方法并不是绝对安全的,虽然将其声明为 private,但是在类内部的 member function 和 friend 类中还是有可能调用的,如下所示(具体代码参考 Ex3):
/tmp/ccuFJ2sv.o: In function `HomeForSale::test()': main.cpp:(.text._ZN11HomeForSale4testEv[_ZN11HomeForSale4testEv]+0x36): undefined reference to `HomeForSale::HomeForSale(HomeForSale const&)' collect2: error: ld returned 1 exit status
/** * this class should not be copyable */ classHomeForSale:public Uncopyable { public: HomeForSale() {}
voidtest(){
HomeForSale h1; HomeForSale h2 = h1; } };
上述代码中 HomeForSale::test() 会在编译器失败并报以下错误:
1 2 3 4 5 6 7 8 9 10 11
main.cpp: In member function ‘void HomeForSale::test()’: main.cpp:20:26: error: use of deleted function ‘HomeForSale::HomeForSale(const HomeForSale&)’ HomeForSale h2 = h1; ^~ main.cpp:13:7: note: ‘HomeForSale::HomeForSale(const HomeForSale&)’ is implicitly deleted because the default definition would be ill-formed: class HomeForSale: public Uncopyable { ^~~~~~~~~~~ main.cpp:13:7: error: ‘Uncopyable::Uncopyable(const Uncopyable&)’ is private within this context main.cpp:6:5: note: declared private here Uncopyable(const Uncopyable&); ^~~~~~~~~~
main.cpp: In member function ‘void HomeForSale::test()’: main.cpp:15:26: error: use of deleted function ‘HomeForSale::HomeForSale(const HomeForSale&)’ HomeForSale h2 = h1; ^~ main.cpp:9:5: note: declared here HomeForSale(const HomeForSale&) = delete; ^~~~~~~~~~~ main.cpp:16:26: error: use of deleted function ‘HomeForSale::HomeForSale(const HomeForSale&)’ HomeForSale h3(h2); ^ main.cpp:9:5: note: declared here HomeForSale(const HomeForSale&) = delete; ^~~~~~~~~~~