Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
859 views
in Technique[技术] by (71.8m points)

constructor - C++ How does implicit construction work, struct initialization?

I have a question about implicit constructors. So let's say I have the following scenario:


struct MyStruct1 {
    bool myBool1 = false;
    bool myBool2 = false;
    MyStruct1() = default;
    MyStruct1(bool val)
        : myBool1(val)
        , myBool2(val)
    {}
};

struct MyStruct2 {
    MyStruct1 myStruct1;
};

Now what I want to know is if 1 and 2 are equivalent below:

1)

int main() {

    MyStruct2 myStruct2;
    myStruct2.myStruct1 = true;
}
int main() {

    MyStruct2 myStruct2;
    myStruct2.myStruct1 = MyStruct1{true};
}

Is that how implicit constructors works? Or is there something else at play here?

question from:https://stackoverflow.com/questions/65925572/c-how-does-implicit-construction-work-struct-initialization

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Yes, that is part of how it works, but there is more to it. It isn't only one-parameter constructors that can be explicit. You can do it for any constructor regardless of number of parameters, better explained by code:

#include <memory>

struct MyStruct1 {
    bool myBool1 = false;
    bool myBool2 = false;
    
    explicit MyStruct1(bool val1 = false, bool val2 = false)
        : myBool1(val1)
        , myBool2(val2)
    {}

};

void func (const MyStruct1& myStruct = {}) // This fails if constructor is explicit
{
    // do something with struct
}

MyStruct1 func2 (bool a)
{
    if (!a) {
        return {}; // Returning default like this fails if constructor is explicit
    } 
    return {true, false}; // Fails if constructor is explicit
}

int main()
{
    auto msp = std::make_unique<MyStruct1>(true, false); // Perfect forwarding is always OK

    func({true, false});            // Fails to compile if constructor is explicit
    func(MyStruct1{true, false});   // Always OK
    MyStruct1 ms1 = {true, false};  // Fails to compile if constructor is explicit
    MyStruct1 ms2{true, false};     // Always OK
    MyStruct1 ms3 = {};             // Fails if constructor is explicit
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...