相关疑难解决方法(0)

隐式转换在现代C++中是好还是坏?

这个提案中:

N3830 Scoped Resource - 标准库的通用RAII包装器

scoped_resource提出了RAII包装器.

在第4页,有一些代码如下:

auto hFile = std::make_scoped_resource(
      ...
    );    
...

// cast operator makes it seamless to use with other APIs needing a HANDLE
ReadFile(hFile, ...);
Run Code Online (Sandbox Code Playgroud)

Win32 API ReadFile()采用原始 HANDLE参数,而不是hFile实例scoped_resource,因此为了使上述代码有效,有一个隐式转换运算符scoped_resource.

但是,避免这种隐性转换不是"现代"建议吗?

例如,ATL/MFC CString具有隐式转换(强制转换操作符)到LPCTSTR(const char/wchar_t*即原始C字符串指针),而STL字符串具有显式 c_str()方法.

类似地,智能指针unique_ptr具有访问底层包装指针的显式 get()方法; 此博客文章中也出现了针对隐式转换的建议:

读者问答:为什么现代智能指针不会隐式转换为*?

那么,对于现代C++来说,这些隐式转换(如ATL/MFC CString和新提出的scoped_resource …

c++ implicit-conversion c++11

13
推荐指数
1
解决办法
2079
查看次数

标签 统计

c++ ×1

c++11 ×1

implicit-conversion ×1