samedi 23 juillet 2022

braced-initialization allows creation of temporary of a *private* struct

I just read the following article from Raymond Chen's excellent 'The Old New Thing': https://devblogs.microsoft.com/oldnewthing/20210719-00/?p=105454

I have a question about this, best described in the following code snippet. Why is the initialization of 'x3' allowed at all? I don't see any semantic difference between the initialization of 'x2' and 'x3' below.

#include <memory>

class X
{
    struct PrivateTag {};   // default constructor is *NOT* explicit
public:
    X(PrivateTag) {}
    static auto Create() -> std::unique_ptr<X> 
    {
        return std::make_unique<X>(PrivateTag{});
    }
};

int main()
{
    auto x1 = X::Create();          // ok:    proper way to create this
  //auto x2 = X(X::PrivateTag{});   // error: cannot access private struct
    auto x3 = X({});                // ok:    why ?!
}

Aucun commentaire:

Enregistrer un commentaire