The copy constructor with default parameters is never called

Why is the output of the following program only int3 , not int3&4 ?

 #include <iostream> class B { public: explicit B(int i) { std::cout<<"int"<<i; } B(const B& rhs, int i = 0) { std::cout<<"&"<<i; } }; int main(int, char**) { B b(B(3), 4); } 

Command: clang++ test.cpp -O0

Compiler: Apple clang version 3.0 (tags / Apple / clang-211.12) (based on LLVM 3.0svn)

+6
source share
3 answers

It was a bug in clang that was fixed. Copy-exception was incorrectly applied to the constructor call because clang did not check how many arguments were provided before concluding that it was a copy construct.

The fix will be in the upcoming clang 3.1 release.

+1
source

Looks like you found the quirk compiler :)

If you change your compiler version to anything other than LLVM 3.0, the output will be int3 & 4.

This prints int3 & 4 to LLVm 3.0, so it seems to be related to the fact that B (3) is a temporary object:

 class B { public: explicit B(int i) { std::cout<<"int"<<i; } B(const B& rhs, int i = 0) { std::cout<<"&"<<i; } }; int main(int, char**) { B a(3); B b(a, 4); } 
+3
source

Most likely, RVO and NRVO ate your code. These special conditions allow the compiler to silently delete copies of objects that would otherwise be followed by the language. Since no copy was made as a result, the code never prints the instruction in the copy constructor.

0
source

Source: https://habr.com/ru/post/909685/


All Articles