Summary:
File has a default constructor so it can be initialized late, but it
doesn't have a good canonical way to see if it's been initialized. This adds an
//explicit// operator bool so you can test files like `if (file) ...`.
Test Plan: Unit tests
Reviewed By: chaoyc@fb.com
FB internal diff:
D726914
*/
int fd() const { return fd_; }
+ /**
+ * Returns 'true' iff the file was successfully opened.
+ */
+ explicit operator bool() const {
+ return fd_ >= 0;
+ }
+
/**
* If we own the file descriptor, close the file and throw on error.
* Otherwise, do nothing.
EXPECT_CONTAINS(e.what(), "0666");
}
}
+
+TEST(File, Truthy) {
+ File temp = File::temporary();
+
+ EXPECT_TRUE(bool(temp));
+
+ if (temp) {
+ ;
+ } else {
+ EXPECT_FALSE(true);
+ }
+
+ if (File file = File::temporary()) {
+ ;
+ } else {
+ EXPECT_FALSE(true);
+ }
+
+ EXPECT_FALSE(bool(File()));
+ if (File()) {
+ EXPECT_TRUE(false);
+ }
+ if (File notOpened = File()) {
+ EXPECT_TRUE(false);
+ }
+}