Typumwandlungskonstruktor
-
huhu ihrs,
irgendwie steh ich grad aufm Schlauch (ist auch schon spät xD),
aufjedenfall compiliert der Compiler das nicht.Error:
no matching function for call toA::A(A)' initializing temporary from result ofA::A(int)'Wieso kann er das tmp Object nicht in den Copy-Constructor reinstecken ??
#include <iostream> using namespace std; class A { public: A(int i){} A(A& ori) {} }; int main() { A a = 1; return 0; }thx schonmal

-
Versuch mal
const A&.
-
hrhr ok^^
aber wieso muss es const sein ?
ist das tmp Object const ?
-
Nein, aber temporäre Objekte können nur als Argumente von Funktionen mit Const-Referenz-Parametern genommen werden. Das liegt daran, dass in C++ nur Referenzen auf
consttemporäre Objekte binden können.int& ref = 1; // Fehler const int& cref = 1; // OK
-
ah okay thx @ nexus
-
Hmm ist interessant, dass der VS2008 Compiler es erlaubt ohne Warnung auszugeben, bei mir zumindest...
-
joa VS 05 auch
-
Soviel ich weiss, ist die Erstellung eines temporären Objekts bei
A a = 1im Gegensatz zu
A a(1);implementierungsabhängig. Der Kopierkonstruktor muss nicht zwingend involviert sein.
Ein Beispiel aus dem C++-Standard; hier allerdings auf ein Objekt, das bereits Typ
Xhat, bezogen. Ich bin mir daher nicht ganz sicher, ob implizite Konvertierungen durch entsprechende Konstruktoren auch darunter fallen, aber meines Erachtens wäre dies logisch.12.2/2 schrieb:
[Example:
class X { // ... public: // ... X(int); X(const X&); ˜X(); }; X f(X); void g() { X a(1); X b = f(X(2)); a = f(a); }Here, an implementation might use a temporary in which to construct X(2) before passing it to f() using X’s copy-constructor; alternatively, X(2) might be constructed in the space used to hold the argument. Also, a temporary might be used to hold the result of f(X(2)) before copying it to b using X’s copyconstructor; alternatively, f()’s result might be constructed in b. On the other hand, the expression a=f(a) requires a temporary for either the argument a or the result of f(a) to avoid undesired aliasing of a. ]