Pretend my unique_ptr is a reference?

I have code that looks like this:
1
2
3
4
5
6
std::unique_ptr<Foobar> pFoobar = FoobarFactory();
Foobar& foobar = *pFoobar; // fix'd!

foobar.Adjuvant();
foobar.Acutance();
foobar.Scarper();

Due to my excessive laziness, I only added line 2 to not have to change all my " . "s to " -> "s (dots to arrows).

But I want to be even lazier! I want something like:

1
2
3
4
5
magic<Foobar> foobar = magic(FoobarFactory());

foobar.Adjuvant();
foobar.Acutance();
foobar.Scarper();

Is it possible to learn this power?

Note: Changing the return type of FoobarFactory is also acceptable, but I cannot use forced copy "elision" (prvalue) due to needing to initialize things after construction of the initial Foobar object. The type Foobar is not copy-constructable, nor copy-assignable.

For completeness, here is FoobarFactory():
1
2
3
4
5
6
7
8
9
std::unique_ptr<Foobar> FoobarFactory() {

    // lots of initialization goes here [...]

    auto pFoobar = std::make_unique<Foobar>( [...] );
    pFoobar->InitializeForReals();

    return pFoobar;
}
Last edited on
I thought of having a wrapper class like this:
1
2
3
4
5
template<typename T>
struct Ref {
    std::unique_ptr<T> ptr;
    // ...
}

the problem is, you can't overload the "." (dot) operator. Maybe I should should just stop being lazy and use the pointer syntax as God intended.

Edit: Turns out I am completely trying to reinvent the wheel, Bjarne linked this article[1] in an SO post[2], which discusses almost the same thing.
[1] http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/n4477.pdf
[2] https://stackoverflow.com/questions/42183631/inability-to-overload-dot-operator-in-c

I can't think of any other good way to extend the lifetime of the unique_ptr. I thought of a static variable, but that destroys the RAII-destructability, thread safety, etc.
Last edited on
Registered users can post here. Sign in or register to post.