PragmaTwice commented on code in PR #768: URL: https://github.com/apache/incubator-kvrocks/pull/768#discussion_r946831355
########## tests/cppunit/status_test.cc: ########## @@ -0,0 +1,146 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ + +#include <gtest/gtest.h> + +#include <memory> +#include <status.h> + +TEST(StatusOr, Scalar) { + auto f = [](int x) -> StatusOr<int> { + if (x > 10) { + return {Status::NotOK, "x large than 10"}; + } + + return 2 * x + 5; + }; + + ASSERT_EQ(*f(1), 7); + ASSERT_EQ(*f(5), 15); + ASSERT_EQ(f(7).GetValue(), 19); + ASSERT_EQ(f(7).GetCode(), Status::cOK); + ASSERT_EQ(f(7).Msg(), "ok"); + ASSERT_TRUE(f(6)); + ASSERT_EQ(f(11).GetCode(), Status::NotOK); + ASSERT_EQ(f(11).Msg(), "x large than 10"); Review Comment: Hi @tisonkun, thanks for your review. > I wonder if we can generate a compile time error instead of runtime fatal in this case. Good idea. We consider an example for this: ```c++ auto res = someProcess(...); // get result typed StatusOr<T> // we cannot deref `res` here if(!res) { processError(res.GetCode(), res.Msg()); /* or */ return res; // we cannot deref `res` here } doSomething(*res); // we can deref it ``` In this example, only the `doSomething` part can actually dereference the `res`. We cannot dereference it both before `if(!res)` and inside `if(!res)`. So only in the execution path with the condition `res.IsOk() == true` being satisfied, we can dereference `res`, It is hardly to express in compile time, since it is related to the control flow. Like a raw/smart pointer, we should check it does point to a value (not null) before dereference it. I have implemented a checker in Clang Static Analyzer that checks whether a type like `StatusOr` is dereferenced after checking `IsOk()`, and I think it can be done in this way in the future. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
