1

please check out the code below :

#include <iostream>
using namespace std;
struct A{
    A(char* str) { cout << "default called" << endl; }
    A(const A &a) { cout << "copy called" << endl; }
};
int main() {
    A obj  = "str";
}

the Output is :

default called

why when i initialize object ,the consturctor of temprorary object isnt called ?? doesnt

A obj  = "str";

turn into

A obj = A("str") // so why consturctor of temprorary object isnt called ?? 

???

i know about Copy elision little bit that why copy constructor of obj isnt called but why cosntructor of temprorary ojbect isnt called ??

Thanks!

Satar
  • 37
  • 7
  • 1
    TL;DR of the dupe: This is an optimization. The compiler can skip making a temporary and copying and instead directly construct the object in the destination – NathanOliver Jul 28 '20 at 18:54
  • @NathanOliver Is it though? [It seems](https://en.cppreference.com/w/cpp/language/copy_initialization) it should always invoke the constructor directly. – HolyBlackCat Jul 28 '20 at 19:21
  • 1
    @HolyBlackCat Not seeing on that page where it disagrees with what I said. The third bullet point covers this case and it has in it *The last step is usually optimized out and the result of the conversion is constructed directly in the memory allocated for the target object* – NathanOliver Jul 28 '20 at 19:25
  • @NathanOliver Yep, I stand corrected. Didn't read it properly. – HolyBlackCat Jul 28 '20 at 19:27
  • @NathanOliver Are you mean, instead of doing it in two steps(1- call constructor for temporary 2- copy constructor for obj) ,The compiler for optimization does char* direct initialize and this is done in one step ?? Is what I said absolutely true?? and does the compiler actually work like that? – Satar Jul 29 '20 at 02:14
  • Yes. Basically,, `A obj = "str";` becomes `A obj("str");`, and this is allowed by the standard via the quote in the second answer on the dupe target. even if the copy constructor has side affects, the standard allows the compiler to ignore them and directly construct the object. This is a performance win with basically no down side. – NathanOliver Jul 29 '20 at 02:25
  • @NathanOliver i got it ,thanks a lot! – Satar Jul 29 '20 at 02:28

1 Answers1

-2

When you create an object by assignment C++ treats it as a constructor call.

Zan Lynx
  • 53,022
  • 10
  • 79
  • 131