我可以在同一表达式中多次使用该对象而不安全地对其进行修改吗?

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_在同一表达式中两次使用它而不修改它是否定义明确?谢谢!

Nat*_*ica 5

使用index两次

return (*check(index_, "dereferencing unbound StrblobPtr!"))[index_];
Run Code Online (Sandbox Code Playgroud)

只要您不修改它就可以。

不好的是,您无条件地间接了指针。您说check可以返回一个空指针。通过空指针间接进行是未定义的行为。您需要通过首先检查返回值来确保避免这种情况。如果为null,则您需要返回一个标记或引发异常。

  • @ItachiUchiwa哦,那很好。您说过*返回一个std :: shared_ptr为null或指向一个对象*,因此我认为`check`实际上可以返回一个null指针。如果它仅返回有效指针或抛出异常,那么您确实可以间接访问该指针而不会出现问题。 (3认同)