c++ - Not expected constructor called -
i'm looking c++11 move constructors doesn't work. in fact issue before started writing such constructor. here's code snipped:
#include <iostream> #include <string> #include <sstream> class object { static std::ostream& log(object &obj) { std::cout << "object::id = " << obj.mid << "::"; return std::cout; } unsigned mid = 0; std::string *mtext = nullptr; unsigned nextuniqueid() const { static unsigned id = 0; return ++id; } const std::string textinfo() const { std::ostringstream oss; oss << "mtext @ " << &mtext; if (mtext) oss << " = " << *mtext; return oss.str(); } public: object() = delete; object& operator= (const object&) = delete; explicit object(const std::string& str) : mid(this->nextuniqueid()), mtext(new std::string(str)) { object::log(*this) << "constructor::one-argument\n"; } object(const object& obj) : mid(this->nextuniqueid()), mtext(new std::string(*obj.mtext)) { object::log(*this) << "constructor::copy\n"; } virtual ~object() { object::log(*this) << "destructor::" << this->textinfo() << "\n"; if (mtext) { delete mtext; mtext = nullptr; } } }; static object get_object() { return object("random text"); } int main(int argc, char **argv) { object a("first object"); // ok /* * expected behaviour: inside get_object() function new object created copied * variable b. new id should given. */ object b = get_object(); // hell?! not expected! why? std::cout << std::endl; return 0; }
the expected output similiar this:
object::id = 1::constructor::one-argument object::id = 2::constructor::one-argument object::id = 2::destructor::mtext @ 0x7fff32c25f70 = random text object::id = 3::constructor::copy object::id = 3::destructor::mtext @ <different in id=2> = random text object::id = 1::destructor::mtext @ 0x7fff32c25f90 = first object
i instead:
object::id = 1::constructor::one-argument object::id = 2::constructor::one-argument object::id = 2::destructor::mtext @ 0x7fff32c25f70 = random text object::id = 1::destructor::mtext @ 0x7fff32c25f90 = first object
which looks variable b
created on spot (something inline
maybe?). frankly speaking don't know what's going on, can explain?
the compiler allowed apply "return value optimization" rvo , that's why copy optimized out. note standard allows despite side effects related output message
Comments
Post a Comment