Fragen zum auto_ptr
-
Ich lese gerade "Die C++ Standardbibliothek" und im Abschnitt über auto_ptr ist Code der sich mit meinem Visual Studio 7.0 nicht compilieren lässt:
auto_ptr<string> ptr (new string("My string")); // Geht auto_ptr<string> ptr1 = new string("My string"); // Geht nicht, sollte laut Buch aber so gehen
error C2440: 'Initialisierung': 'std::string *' kann nicht in 'std::auto_ptr<_Ty>' konvertiert werden
with
[
_Ty=std::string
]Woran liegts?
-
dagewg schrieb:
Woran liegts?
iirc sind alle konstruktoren von auto_ptr explicit.
-
Den Satz verstehe ich nicht
-
Schau dir das Schlüsselwort explicit an
#include <iostream> class foo { int i; public: foo(int j) : i(j) { std::cout << "foo()\n"; } }; class bar { int i; public: explicit bar(int j) : i(j) { std::cout << "bar()\n"; } }; int main() { foo f0=10; // Geht, Konstruktor wird aufgerufen foo f1(20); // Geht, Konstruktor wird explizit aufgerufen bar b0=10; // Geht nicht, da der Konstruktor immer explizit aufgerufen werden muss bar b1(20); // Geht, Konstruktor wird explizit aufgerufen }
Das explizite Aufrufen des Konstruktors verhindert, dass es zu impliziten Typumwandlungen kommt.
http://www.gotw.ca/gotw/004.htm
http://www.gotw.ca/gotw/062.htm
-
danke
das hat geholfen