8 ms·
I can't edit my original comment anymore, so I'll just write a clarification in the reply. Many people have pointed out that C++17 has std::optional. While tha
by CodeMage 7y ago
I can't edit my original comment anymore, so I'll just write a clarification in the reply.
Many people have pointed out that C++17 has std::optional. While that's true, I don't think it'll deprecate raw pointers. I'll try to explain why.
Here's an example you can paste, compile and run:
#include <iostream>
#include <memory>
struct foo
{
int thingamajig;
};
void borrow_optional_foo(foo * borrowed)
{
if (borrowed != nullptr)
{
borrowed->thingamajig = 42;
}
}
int main()
{
std::unique_ptr<foo> owned = std::make_unique<foo>();
owned->thingamajig = 17;
std::cout << owned->thingamajig << std::endl;
borrow_optional_foo(owned.get());
std::cout << owned->thingamajig << std::endl;
return 0;
}
If you run it, it should print:
17
42
What would it look like if we wanted to use std::optional and get the same behavior?
#include <iostream>
#include <functional>
#include <memory>
#include <optional>
struct foo
{
int thingamajig;
};
void borrow_optional_foo(std::optional<std::reference_wrapper<foo>> borrowed)
{
if (borrowed)
{
borrowed->get().thingamajig = 42;
}
}
int main()
{
std::unique_ptr<foo> owned = std::make_unique<foo>();
owned->thingamajig = 17;
std::cout << owned->thingamajig << std::endl;
borrow_optional_foo(std::make_optional(std::ref(*(owned.get()))));
std::cout << owned->thingamajig << std::endl;
return 0;
}
As you can see, there's a tradeoff involved. On the one hand, you get crystal clear, descriptive type: std::optional<std::reference_wrapper<foo>> is clearly an optional reference to foo.
On the other hand, using it is absolutely atrocious: you have to write borrowed->get().thingamajig as opposed to borrowed->thingamajig, and std::make_optional(std::ref(*(owned.get()))) as opposed to owned.get()
Does it work? Absolutely. Is it crystal clear? Indisputably so. Will it deprecate raw pointers? I really, really doubt it, but that's just my opinion.
- jez 7y agoThis is a great reply and I think it echoes what I've seen written elsewhere. For example, this one by Herb Sutter: https://herbsutter.com/2013/06/05/gotw-91-solution-smart-pointer-parameters/ https://herbsutter.com/2013/06/05/gotw-91-solution-smart-poi...