C++ 隐式构造如何工作,结构初始化?
C++ How does implicit construction work, struct initialization?
我有一个关于隐式构造函数的问题。
假设我有以下情况:
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};
}
隐式构造函数就是这样工作的吗?
还是这里有其他事情在起作用?
是的,这是它工作原理的一部分,但还有更多。不仅仅是单参数构造函数可以是显式的。无论参数数量如何,您都可以为任何构造函数执行此操作,代码更好地解释:
#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
}
我有一个关于隐式构造函数的问题。 假设我有以下情况:
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};
}
隐式构造函数就是这样工作的吗? 还是这里有其他事情在起作用?
是的,这是它工作原理的一部分,但还有更多。不仅仅是单参数构造函数可以是显式的。无论参数数量如何,您都可以为任何构造函数执行此操作,代码更好地解释:
#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
}