在哪里调用复制构造函数? 我在Me.CPP文件中写了一段C++代码,我正在尝试了解它是如何工作的。
首先,我定义了一个类“Value”: 其中打印以下内容:在哪里调用复制构造函数? 我在Me.CPP文件中写了一段C++代码,我正在尝试了解它是如何工作的。,c++,g++,copy-constructor,C++,G++,Copy Constructor,首先,我定义了一个类“Value”: 其中打印以下内容: Creating v = 10 Ctor called Creating v = 20 Ctor called 我再次编译代码,但没有优化复制构造函数: g++ --std=c++11 -fno-elide-constructors -c main.cpp g++ main.o -o main.exe ./main.exe 现在,它打印以下内容: Creating v = 10 Ctor called Copy Ctor called
Creating v = 10
Ctor called
Creating v = 20
Ctor called
我再次编译代码,但没有优化复制构造函数:
g++ --std=c++11 -fno-elide-constructors -c main.cpp
g++ main.o -o main.exe
./main.exe
现在,它打印以下内容:
Creating v = 10
Ctor called
Copy Ctor called. V = 10
Creating v = 20
Ctor called
Copy Ctor called. V = 20
Copy Ctor called. V = 20
Copy Ctor called. V = 20
不知道为什么它会多次调用复制构造函数。我是一个C++ NoOB,想更好地理解流程。我很想知道这段代码是如何运行的,以及为什么拷贝构造函数经常被调用。下面是拷贝:
auto v=值(10)代码>使用
中的复制构造函数初始化值(10)
v
autonewvalue=Value(v.rawValue()*2)代码>使用
中的复制构造函数初始化Value(v.rawValue()*2)
newValue
使用返回newValue
中的复制构造函数初始化返回值newValue
auto v2=doubleValue(v)代码>使用返回值中的复制构造函数初始化
v2
auto v=值(10)代码>使用
中的复制构造函数初始化值(10)
v
autonewvalue=Value(v.rawValue()*2)代码>使用
中的复制构造函数初始化Value(v.rawValue()*2)
newValue
使用返回newValue
中的复制构造函数初始化返回值newValue
auto v2=doubleValue(v)代码>使用返回值中的复制构造函数初始化
v2
Creating v = 10
Ctor called
Creating v = 20
Ctor called
g++ --std=c++11 -fno-elide-constructors -c main.cpp
g++ main.o -o main.exe
./main.exe
Creating v = 10
Ctor called
Copy Ctor called. V = 10
Creating v = 20
Ctor called
Copy Ctor called. V = 20
Copy Ctor called. V = 20
Copy Ctor called. V = 20