Ita*_*iwa 4 c++ operator-precedence
我已经在C ++入门5版中看到了这个例子,它讨论了智能指针。我有课StrBlobPtr,其可以作为一个伴侣StrBlob。
的成员之一StrBlobPtr是deref:
std::string& StrBlobPtr::deref() const
{
auto p = check(curr, "dereference past end");
return (*p)[curr]; // (*p) is the vector to which this object points
}
Run Code Online (Sandbox Code Playgroud)
check返回一个std::shared_ptrnull或指向一个对象。
我只想知道我是否可以直接通过调用来制作return语句check:
std::string& StrblobPtr::deref() {
return (*check(index_, "dereferencing unbound StrblobPtr!"))[index_];
}
Run Code Online (Sandbox Code Playgroud)那么index_在同一表达式中两次使用它而不修改它是否定义明确?谢谢!
使用index两次
return (*check(index_, "dereferencing unbound StrblobPtr!"))[index_];
Run Code Online (Sandbox Code Playgroud)
只要您不修改它就可以。
不好的是,您无条件地间接了指针。您说check可以返回一个空指针。通过空指针间接进行是未定义的行为。您需要通过首先检查返回值来确保避免这种情况。如果为null,则您需要返回一个标记或引发异常。