[英]how to pass in a std::shared_ptr but do “pass by reference” job?
I have a main function that takes in a reference of a class object and try to update it via foo()
and bar()
, however, the bar()
only allows to pass into a shared_ptr type. 我有一个主要函数,该函数接受类对象的引用,并尝试通过
foo()
和bar()
对其进行更新,但是, bar()
仅允许传递为shared_ptr类型。 How can I guarantee it behaves as expected, assuming I am NOT allowed to modify the signature of bar()
. 假设不允许我修改
bar()
的签名,我如何保证它的行为符合预期。
void foo(MyStruct& s) {
modifyS(s);
}
void bar(std::shared_ptr<MyStruct> s) {
modifySAgain(s);
}
mainFunction(MyStruct& s) {
foo(s);
// bar(?) how should I do here such that s would be modified by bar()
// bar(std::make_shared<Mystruct>(std::move(s)) ?
}
You could use a null-aliasing shared pointer: 您可以使用null别名共享指针:
bar(std::shared_ptr<MyStruct>(std::shared_ptr<MyStruct>(), &s));
The temporary shared pointer created in this call shares ownership with a null shared pointer, so it does nothing on destruction. 在此调用中创建的临时共享指针与空共享指针共享所有权,因此在销毁时不执行任何操作。
This is perhaps a bit of a hack. 这也许有点骇人听闻。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.