欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

C++ // 习题 12.17 下列哪些 unique_ptr 声明是合法的,哪些声明可能导致随后的程序错误?解释每个错误的问题所在。

最编程 2024-04-18 18:02:47
...

C++ Primer(第5版) 练习 12.17

练习 12.17 下面的unique_ptr声明中,哪些是合法的,哪些可能导致后续的程序错误?解释每个错误的问题在哪里。

int ix = 1024, *pi = &ix, *pi2 = new int(2048);
typedef unique_ptr<int> IntP;
( a ) IntP p0(ix);
( b ) IntP p1(pi);
( c ) IntP p2(pi2);
( d ) IntP p3(&ix);
( e ) IntP p4(new int(2048));
( f ) IntP p5(p2.get());
环境:Linux Ubuntu(云服务器)
工具:vim

 

代码块
int ix = 1024, *pi = &ix, *pi2 = new int(2048);
typedef unique_ptr<int> IntP;
//非法,初始化unique_ptr必须采用直接初始化形式
( a ) IntP p0(ix);
//合法
( b ) IntP p1(pi);
//合法
( c ) IntP p2(pi2);
//合法
( d ) IntP p3(&ix);
//合法
( e ) IntP p4(new int(2048));
//合法
( f ) IntP p5(p2.get());