英文:
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& 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.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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论