Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/154.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/powerbi/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 在c+中的聚合初始化中是否可以执行复制省略+;17?_C++_C++17_Copy Elision_Aggregate Initialization - Fatal编程技术网

C++ 在c+中的聚合初始化中是否可以执行复制省略+;17?

C++ 在c+中的聚合初始化中是否可以执行复制省略+;17?,c++,c++17,copy-elision,aggregate-initialization,C++,C++17,Copy Elision,Aggregate Initialization,鉴于: /C++17 #包括 结构Foo{ int i; std::字符串str; }; int main(){ Foo-Foo{1,std::string(“你好,世界!”)}; } Foo::i和Foo::str可以直接从1和std::string(…)初始化,而不是复制到它们中,并解释为什么可以/不能使用C++17标准(可能是一些用于测试的代码)? 如果不能,需要多少拷贝?聚合初始化基本上执行元素级拷贝初始化。因此: //C++17 #include <string> str

鉴于:

/C++17
#包括
结构Foo{
int i;
std::字符串str;
};
int main(){
Foo-Foo{1,std::string(“你好,世界!”)};
}
Foo::i
Foo::str
可以直接从
1
std::string(…)
初始化,而不是复制到它们中,并解释为什么可以/不能使用C++17标准(可能是一些用于测试的代码)?
如果不能,需要多少拷贝?

聚合初始化基本上执行元素级拷贝初始化。因此:

//C++17
#include <string>
struct Foo {
    int i;
    std::string str;
};

int main() {
    Foo foo{1, std::string("Hello, world!")};
}
执行与以下相同的初始化:

struct Foo {
    int i;
    std::string str;
};

Foo foo{1, std::string("Hello, world!")};
我们在C++17中有这样一句话:

如果初始值设定项表达式是prvalue,并且源类型的cv非限定版本与目标的类是同一个类,则初始值设定项表达式用于初始化目标对象。[ 示例:
tx=T(T(T());
调用
T
默认构造函数来初始化
x
- 结束示例 ]

这意味着第二次初始化的行为必须与您编写的:

int i = 1;
std::string str = std::string("Hello, world!");
即零份


下面的示例很好地演示了新规则:

std::string str("Hello, world!");

聚合初始化基本上执行元素复制初始化。因此:

//C++17
#include <string>
struct Foo {
    int i;
    std::string str;
};

int main() {
    Foo foo{1, std::string("Hello, world!")};
}
执行与以下相同的初始化:

struct Foo {
    int i;
    std::string str;
};

Foo foo{1, std::string("Hello, world!")};
我们在C++17中有这样一句话:

如果初始值设定项表达式是prvalue,并且源类型的cv非限定版本与目标的类是同一个类,则初始值设定项表达式用于初始化目标对象[ 示例:
tx=T(T(T());
调用
T
默认构造函数来初始化
x
- 结束示例 ]

这意味着第二次初始化的行为必须与您编写的:

int i = 1;
std::string str = std::string("Hello, world!");
即零份


下面的示例很好地演示了新规则:

std::string str("Hello, world!");