vector
是一个具有两个公共成员的结构体;一个打印 integer constructor called
的参数化构造函数;打印 copy constructor called
的复制构造函数;打印 move constructor called
. 的移动构造函数
如果
makeVectorx5y5IfNotZero
是 {5, 5}
,则函数 arg
返回向量 0
。否则返回 {2, 2}
。
main
函数使用vector A
构造makeVectorx5y5IfNotZero(1)
并使用vector B
构造makeVectorx5y5IfNotZero(0)
。这是代码
#include <iostream>
struct vector{
int X, Y;
vector(int X, int Y) : X(X), Y(Y){
printf("integer constructor called\n");
}
vector(const vector& other): X(other.X), Y(other.Y){
printf("copy constructor called\n");
}
vector(vector&& other): X(other.X), Y(other.Y){
printf("move constructor called\n");
}
};
vector makeVectorx5y5IfNotZero(bool Arg){
if(Arg){
vector A(0, 0);
A.X = 5;
A.Y = 5;
return A;
}
else {
vector B(1,1);
B.X = 2;
B.Y = 2;
return B;
}
}
int main(){
printf("Making Vector\n");
vector A = makeVectorx5y5IfNotZero(1);
printf("Made Vector\n");
printf("Making Another Vector\n");
vector B = makeVectorx5y5IfNotZero(0);
printf("Made Vector\n");
}
这段代码的输出是:
C:\copy elision>g++ --version
g++ (Rev3, Built by MSYS2 project) 14.1.0
Copyright (C) 2024 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
C:\copy elision> g++ question.cpp -std=c++23
C:\copy elision>a
Making Vector
integer constructor called
Made Vector
Making Another Vector
integer constructor called
move constructor called
Made Vector
C:\copy elision>
但是,由于 NRVO,我期望以下输出
Making Vector
integer constructor called
Made Vector
Making Another Vector
integer constructor called
Made Vector
我将非常感谢您解释为什么'makeVectorx5y5IfNotZero
B
Bis moved into the local variable
main`的局部变量of
而不是仅仅在同一内存地址构造单个变量。
正如 @PepijnKramer 所说,这是 gcc 的限制。在此视频中对此进行了更详细的讨论 C++ Weekly - Ep 456 - RVO + Trivial Types = Faster Code