I have the following:
#include <iostream>
#include <utility>
class T {
public:
T() {std::cout << "Default constructor called" << std::endl;}
T(const T&) {std::cout << "Copy constructor called" << std::endl;}
};
static T s_t;
T foo() {
return s_t;
}
class A {
public:
A() = delete;
A(T t) : _t(t) {}
private:
T _t;
};
int main() {
std::cout << "Starting main" << std::endl;
A a(foo());
return 0;
}
When I compile it with the line:
g++ -std=c++17 -O3 test.cpp
and run it, I get the following output
Default constructor called
Starting main
Copy constructor called
Copy constructor called
My question is: since the constructor of A
is taking an r-value object of type T
that is only used to initialize _t
, is it possible for the compiler to avoid the second copy operation and just copy s_t
directly into _t
?
(I understand that I can potentially replace the second copy with a move by implementing a move constructor for T
)