C++ API 设计 shared_ptr 和调用函数

huangapple go评论82阅读模式
英文:

C++ API design shared_ptr and calling into functions

问题

I have similar C++ code to this:

struct Data { /* ... */ }
int SomeFunction1(const Data& data) { return 0; }
int SomeFunction2(std::shared_ptr<Data>& data) { return 0; } // this is non-const though
int SomeFunction3(const Data* data) { return 0; } // possibility of receiving nullptr

int main()
{
  auto data = std::make_shared<Data>(); /* initialization somehow */;
  return SomeFunction1(*data); // (1) call get and dereference the pointer
  return SomeFunction2(data); // (2) create an API that accepts the shared pointer
  return SomeFunction3(data) // (3) create an API that accepts raw pointers
}

Please, ignore for the sake of simplicity that I can use a unique_ptr in this specific example.

To me, (1) seems preferable, but I am wondering whether the code at the caller *data is common or rather some kind of design smell?

英文:

I have similar C++ code to this:

struct Data { /* ... */ }
int SomeFunction1(const Data&amp; data) { return 0; }
int SomeFunction2(std::shared_ptr&lt;Data&gt;&amp; data) { return 0; } // this is non-const though
int SomeFunction3(const Data* data) { return 0; } // possibility of receiving nullptr

int main()
{
  auto data = std::make_shared&lt;Data&gt;(); /* initialization somehow */;
  return SomeFunction1(*data.get()); // (1) call get and dereference the pointer
  return SomeFunction2(data); // (2) create an API that accepts the shared pointer
  return SomeFunction3(data.get()) // (3) create an API that accepts raw pointers
}

Please, ignore for the sake of simplicity that I can use a unique_ptr in this specific example.

To me, (1) seems preferable, but I am wondering whether the code at the caller *data.get() is common or rather some kind of design smell?

答案1

得分: 1

是的,shared.get() 通常并不表示一切都顺利。但是,在你的示例中,你不需要使用 get(),因为 std::shared_ptr 重载了 operator*,所以你可以简单地写成 SomeFunction1(*data)

如果该函数不共享对象的所有权,这是首选的做法,这似乎是你的情况。否则,你将不得不复制 std::shared_ptr 对象。

英文:

Yes, shared.get() is not usually an indicator that everything is going well. However, in your example, you don't need get() because std::shared_ptr overloads operator*, so you can simply say SomeFunction1(*data).

This is preferably if the function does not take shared ownership of the object, which seems to be the case. Otherwise you would have to copy the std::shared_ptr object.

huangapple
  • 本文由 发表于 2023年6月13日 15:55:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/76462779.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定