【问题标题】:C++ How does implicit construction work, struct initialization?C++ 隐式构造如何工作,结构初始化?
【发布时间】:2021-01-27 18:53:21
【问题描述】:

我有一个关于隐式构造函数的问题。 所以假设我有以下场景:


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

struct MyStruct2 {
    MyStruct1 myStruct1;
};

现在我想知道下面的 1 和 2 是否等价:

1)

int main() {

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

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

这就是隐式构造函数的工作原理吗? 或者这里还有其他什么在起作用?

【问题讨论】:

  • 我觉得这一定是某些东西的副本,但我还不能完全找到它......但无论哪种方式,是的,这基本上是隐式构造的工作原理。唯一需要注意的是,在这两种情况下,您都在使用 assignment,这会强制从 MyStruct1 调用构造函数
  • 万一你不知道cppinsights,这是一个非常方便的网站,可以解决这类问题。
  • 在这种情况下是的——但如果MyStruct1 有一个explicit 构造函数或重载的赋值运算符会有所不同
  • @florestan 谢谢你,这是一个很好的资源。

标签: c++ constructor implicit-conversion


【解决方案1】:

是的,这是它工作原理的一部分,但还有更多。可以显式的不仅仅是单参数构造函数。无论参数数量如何,您都可以为任何构造函数执行此操作,代码更好地解释:

#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
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-08
    • 1970-01-01
    • 1970-01-01
    • 2012-07-16
    相关资源
    最近更新 更多