这种向布尔的转换是如何工作的
How does this conversion to bool work?
我正在学习Cinder框架。这个框架中有一个类Texture
,它可以这样使用:
Texture myImage;
myImage.loadImage(/*...*/);
if(myImage)
{
// draw the image.
}
我对此感到困惑,因为myImage
是一个对象。用它作为条件对我来说没有意义。我期待着myImage.exist();
这样的东西。所以我遍历了代码,结果发现Texture
类定义了一个转换运算符:
public:
//@{
//! Emulates shared_ptr-like behavior
typedef std::shared_ptr<Obj> Texture::*unspecified_bool_type;
// What is this???
operator unspecified_bool_type() const { return ( mObj.get() == 0 ) ? 0 : &Texture::mObj; }
void reset() { mObj.reset(); }
//@}
Obj定义为:
protected:
struct Obj {
Obj() : mWidth( -1 ), mHeight( -1 ), mCleanWidth( -1 ), mCleanHeight( -1 ), mInternalFormat( -1 ), mTextureID( 0 ), mFlipped( false ), mDeallocatorFunc( 0 ) {}
Obj( int aWidth, int aHeight ) : mInternalFormat( -1 ), mWidth( aWidth ), mHeight( aHeight ), mCleanWidth( aWidth ), mCleanHeight( aHeight ), mFlipped( false ), mTextureID( 0 ), mDeallocatorFunc( 0 ) {}
~Obj();
mutable GLint mWidth, mHeight, mCleanWidth, mCleanHeight;
float mMaxU, mMaxV;
mutable GLint mInternalFormat;
GLenum mTarget;
GLuint mTextureID;
bool mDoNotDispose;
bool mFlipped;
void (*mDeallocatorFunc)(void *refcon);
void *mDeallocatorRefcon;
};
std::shared_ptr<Obj> mObj;
我知道operator int() const
可以简单地将Object更改为int,但未指定的bool_type是如何工作的?当if(myImage)
正在执行时,调试器在operator unspecified_bool_type() const { return ( mObj.get() == 0 ) ? 0 : &Texture::mObj; }
处停止。
我可能对这里的语法有点困惑,是什么
typedef std::shared_ptr<Obj> Texture::*unspecified_bool_type;
刻薄?
void (*mDeallocatorFunc)(void *refcon);
在Obj中,意思是mDeallocatorFunc是Class Obj的成员,Class Obj是指向原型为void xxx(void *)
的函数的函数指针?
这是安全布尔习惯用法。它不使用简单的operator bool()
,因为隐式转换可能会导致该运算符出现各种问题。因此,它使用了一个可以隐式转换为bool
的类型(就像指向成员的指针),这是最不危险的。
幸运的是,C++11中不需要这种破解,因为我们可以编写explicit operator bool
,而不会成为隐式转换的牺牲品。
相关文章:
- QSqlquery prepare()和bindvalue()不工作
- 导入库可以跨dll版本工作吗
- 以螺旋方式打印矩阵的程序.(工作不好)
- 对象指针在c++中是如何工作的
- 为什么在Windows上的VS 2019和Clang 9中"size_t"在没有标题的情况下工作
- VSOMEIP-2个设备之间的通信(TCP/UDP)不工作
- 为字符串中每 N 个字符插入空格的函数没有按照我认为的方式工作?
- C++为线程工作动态地分割例程
- 为什么我的 std::ref 无法按预期工作?
- 布尔比较运算符是如何在C++中工作的
- SampleConsensusPrerejective(ext.RANSAC)是如何真正工作的
- 不确定要在我的main中放入什么才能使我的代码正常工作
- 为什么std::condition_variable notify_all的工作速度比notify_one快(对于随机请
- <<操作员在下面的行中工作
- 有人能解释一下为什么下界是这样工作的吗C++的
- ExtractIconEx:可以工作,但偶尔会崩溃
- C++中的memset函数工作不正常
- 当我在第一个循环中使用"auto"时,它工作正常,但是使用"int"它会给出错误,为什么?
- 链表c++插入,所有情况都已检查,但没有任何工作
- 当 int 方法工作正常时,void 方法有何不同,或者为什么我不能调用 void 方法?