Hi, I'm Bryan.

C++ Beauty

January 26, 2019

I don’t write a lot of C++, most of my coding day is spent bouncing between C# and C, and I fiddle with 6502 assembly on the weekends for sport. C++ has always been this language that I’ve glanced at sideways, mostly restricting myself to idioms that are exceedingly similar to a managed language while building things atop some large and expressive framework like Qt. I’ve lived, and my AV count is low. When I’ve done anything important in a non-managed language, it’s been in C; NDIS LWF here, a high performance TCP proxy, etc.

I recently stumbled on some really beautiful C++ code at work the other day that managed to do two things I was actually quite surprised by:

Unfortunately, I can’t share the source in question, but it got me to wondering about C++ in general. This led me to stumble on this resource management fact that has positively tickled me:

#include <memory>

struct Foo {
        private:
                Foo() {}
};

struct Bar {
        private:
                std::unique_ptr<Foo> _foo;
};

int main() {
        Bar b;
        Bar c = b;
}

Ed. Note: Reduced example to a minimum example for clarity

I wrote this fully expecting some sort of horrible undefined behavior - I’m invoking the copy constructor on an object with a std::unique_ptr member! Ha ha, C++, twiddly dee, I the horrible programmer have read your complexities and dreamt up a means to shoot my own foot!

But I was thwarted. The compiler deleted the copy constructor!

fail.cpp(16): error C2280: 'Bar::Bar(const Bar &)': attempting to reference a deleted function
fail.cpp(12): note: compiler has generated 'Bar::Bar' here
fail.cpp(12): note: 'Bar::Bar(const Bar &)': function was implicitly deleted because a data member 
    invokes a deleted or inaccessible function 
    'std::unique_ptr<Foo,std::default_delete<_Ty>>
        ::unique_ptr(const std::unique_ptr<_Ty,std::default_delete<_Ty>> &)'
        with
        [
            _Ty=Foo
        ]

This is on Visual C++ 19.16 with /std:c++17. I’ve never been so happy to have received a compiler error.