An example problem of copying constructor

recently, when I was watching bilibili"s last video about cPP, I had doubts, so I knocked on the code to run. The result is different from the output in the video. Solve everyone, video address: ideo/av12638525/?p=17" rel=" nofollow noreferrer "> Peking University cPP tutorial 7 minutes and 35 seconds, the source code is as follows:

-sharpinclude <iostream>

using namespace std;

class A
{
public:
    int v;
    
    A(int n)
    {
        v = n;
    }
    
    A(const A & a)
    {
        v = a.v;
        cout <<"Copy constructor called."<<endl;
    }
};

A Func()
{
    A b(4);
    return b;
}

int main()
{
    cout << Func().v << endl;
    return 0;
}

I didn"t output Copy constructor called when I ran it myself. In the video, the author says that the function returns a class An object and then copies it to a temporary variable in the cout statement before it can be called. Variable, the actual running result is not consistent with what he said?

related information:
[root@centos-linux-10 workspace]-sharp gPP copy.cpp
[root@centos-linux-10 workspace]-sharp. / a.out
4
[root@centos-linux-10 workspace]-sharp gcc-v
use built-in specs.
COLLECT_GCC=gcc
COLLECT_LTO_WRAPPER=/usr/libexec/gcc/x86_64-redhat-linux/4.8.5/lto-wrapper
Target: x86_64-redhat-linux
is configured to:.. / configure-- prefix=/usr-- mandir=/usr/share/man-- infodir=/usr/share/info-- with-bugurl= http://bugzilla.redhat.com/bu...-- enable-bootstrap-- Enable-shared-enable-threads=posix-enable-checking=release-with-system-zlib-enable-__cxa_atexit-disable-libunwind-exceptions-enable-gnu-unique-object-enable-linker-build-id with-linker-hash-style=gnu enable-languages=c CPP,objc,obj-cPP,java,fortran,ada,go Lto-enable-plugin-- enable-initfini-array-- disable-libgcj-- with-isl=/builddir/build/BUILD/gcc-4.8.5-20150702/obj-x86_64-redhat-linux/isl-install-- with-cloog=/builddir/build/BUILD/gcc-4.8.5-20150702/obj-x86_64-redhat-linux/cloog-install-- enable-gnu-indirect-function-- with-tune=generic-- with-arch_32=x86-64-- build=x86_64-redhat-linux
Threading model: posix
gcc version 4.8.5 20150623 (Red Hat 4.8.5-36) (GCC)

have I made a mistake? Solve all of you

CPP
Jun.16,2022

has been optimized. RVO can learn about it. Just add a parameter at compile time -fno-elide-constructors

.
Menu