Вопрос

Possible Duplicate:
What’s the motivation behind having copy and direct initialization behave differently?

And by copy initialization, I mean like so:

struct MyStruct
{
    MyStruct(int) {}
    MyStruct(const MyStruct&) {}
};

MyStruct s = 5; // needs *both* the int and copy constructor

Despite programming in C++ for years, I never realized the above code required the copy constructor (thanks to jogojapan). The temporary had always been elided, and as such I never even knew it even existed (at least on a superficial level, despite it being optimized away) until it was pointed out to me.

After a decent amount of googling, I get the idea of how it works. My question is why is it the way it is?

Why didn't the standard make it so that the above example doesn't need the copy constructor? Is there some specific case/example that shows that requiring the copy constructor in this type of initialization is important?

Without a decent explanation of why things are they way they are, I just see this as an annoying artifact, but I'd rather not be ignorant if there's something important that I'm missing.

Это было полезно?

Решение

Copy initialization of an object is ambiguous to direct initialization, both can be used to the same extent in order to set values equal to each other.

int a = 4;
int a = int(4);
int a(4);

all of these calls are ambiguous, they all set a equal to 4. The reason for a copy constructor in the case of an integer is convenience, imagine c++ data types without this

int a(foo(b,r)); //a little messy for a variable declaration
int a = foo(b,r) //ok, cleaner

you also might might to use an implicit and explicit copy constructor, here is an example program that uses a copy constructor explicitly to handle imaginary numbers:

#include <iostream>
using std::cout;
using std::endl;
class complexNumbers {
  double real, img;
public:
  complexNumbers() : real(0), img(0) { }
  complexNumbers(const complexNumbers& c) { real = c.real; img = c.img; }
  explicit complexNumbers( double r, double i = 0.0) { real = r; img = i; }
  friend void display(complexNumbers cx);
};
void display(complexNumbers cx){
  cout<<&quot;Real Part: &quot;<<cx.real<<&quot; Imag Part: &quot;<<cx.img<<endl;
}
int main() {
  complexNumbers one(1);
  display(one);
  complexNumbers two =2;
  display(200);
  return 0;
}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top