+ 1

constructor object as reference

Hi Refer code below: #include <iostream> using namespace std; class test { public: test(int i){} }; int main() { [[maybe_unused]] const test& obj1 = test(1); [[maybe_unused]] const test obj2 = test(1); return 0; } What is the difference between obj1 and obj2? obj2 is not an reference , but obj1 is. Does this mean that obj2 will have copy constructor called? No, right..? So, what's difference? what does obj1 is referring to?

5th Jul 2024, 9:56 AM
Ketan Lalcheta
Ketan Lalcheta - avatar
2 Respuestas
+ 2
obj1 is a reference to the temporary object created by test(1) constructor with no copy constructor called. This implies that the linkage and lifetime of the temporary object will be extended to obj1's due to the reference rule. As for obj2, the copy constructor is definitely called. The process is called copy-initialization. A temporary object of test(1) was called and it's value got assigned to obj2 In obj1, a temporary object of test(1) was created and it becomes referenced by the l-value obj1
5th Jul 2024, 4:03 PM
Mel
0
Hi Melle , Thanks. I had doubt that it should not call copy constructor in both case. Refer code below: It has no call to copy constructor. https://sololearn.com/compiler-playground/cFQz3j6m8A7x/?ref=app
6th Jul 2024, 1:18 PM
Ketan Lalcheta
Ketan Lalcheta - avatar