what are the benefits of using Copy initialization form ?

i know that when we use the copy form (=) the compiler will pass the right-hand
operand to the copy-constructor of that class.

in addition, the compiler can ignore the use copy constructor of in the initialization of nameless temporary like t in the example.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
 struct test {
	int i;
	test(int v) : i(v) {}
};

int main() {
		// the compiler will use copy constructor
	test t = 15; // the compiler will use 15 to construct a temp then pass this temp to the copy constructor of test , equivalent to (test t = test(15);)
	test t1 = t; // the compiler will pass this object to copy constructor of test

		// why not to use the copy constructor MANUALLY
	test t3(test(15)); 
	test t4(t);
}



why not to use direct form to use the copy constructor in order to initialize any object , the parameters of a function and the returned temp rather than copy form?

why does the copy initialization form exist ?
What do the ints do?
1
2
3
4
5
6
// do you prefer the traditional
int foo = 42;
// or
int foo (42);
// or, since C++11
int foo {42};

If you do let the ints to assign, why not do it for all types?

Consistent style.
it's not Consistent style in classes , ints(primitive data types) are not classes, so all theses forms are equivalent !!
Try compiling your program with and without eliding the copy constructor with the command: -fno-elide-constructors and you'll notice some interesting differences.
http://en.cppreference.com/w/cpp/language/copy_elision

Yes, copy elision streamlines.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <iostream>

struct test {
	int i;
	test(int v) : i(v) {
	    std::cout << "from int ";
	}
	test(const test & rhs) : i(rhs.i) {
	    std::cout << "copy ctor ";
	}
	test & operator=(const test & rhs) {
	    i = rhs.i;
	    std::cout << "copy ass ";
	    return *this;
	}
};

int main() {
	std::cout << "t  ";
	test t = 15;
	std::cout << "\nt1 ";
	test t1 = t;
	std::cout << "\nt3 ";
	test t3(test(15)); 
	std::cout << "\nt4 ";
	test t4(t);
	std::cout << "\nt5 ";
	test t5(42);
	std::cout << "\nt6 ";
	test t6{t};
	std::cout << "\nt7 ";
	test t7{42};
	std::cout << '\n';
}



Back to why:
1
2
3
template <typename T> void foo() {
  T bar = 42;
}

Should we not use the old established syntax of primitive types just because the T might be a class?

Was the C++ standardization committee inconsiderate, incompetent and short-sighted when it did allow more than one syntax?
Last edited on
thanks keskiverto , gunnerfunner for replying.
i just wanted to know if there are any benefits that i don't know to use copy over direct form like in parameters and returnd values of functions.
Last edited on
Topic archived. No new replies allowed.