c++ - How works - Pointer / Unique_ptr without new -


foo.h

#include <iostream> #include <memory>  class bar { public:     bar() {};     ~bar() {};     void print() {         std::cout << "hello";     } };  class foo { public:     foo();      ~foo();     void use() {         pteste->print();     } private:     std::unique_ptr<bar> pteste; };  #endif 

main.cpp

#include <memory> #include "foo.h"  int main(int argc, char *argv[])  {     foo s;     s.use();      return 0; } 

why , how works "normally"?

thanks

edit: understand incomplete types, happens when can use unique_ptr without using new , why works

edit2: organized code better question

short answer: doesn't work.

this reference says default constructor of std::unique_ptr creates empty unique pointer, meaning has no associated object.

the reason why code prints hello because statement

std::cout << "hello"; 

doesn't need of bar. static method. maybe compiler inlines function , replaces s.use() std::cout-statement. if call method, won't notice errors since doesn't access memory of bar @ all.

make slight change class , see mean:

class bar { public:     bar() : data(10) {};     ~bar() {};     void print() {         std::cout << "hello, data is: " << data;     }      int data; }; 

now, print accesses invalid memory, because never called new (or better: make_unique). may work , print console, output of data garbage. if you're lucky, application crash.

another reason why appears work (thanks stas):

std::unique_ptr defines operator->, returns contained pointer, not check if pointer points valid memory. pteste-> won't throw exception.


Comments

Popular posts from this blog

c# - How to get the current UAC mode -

postgresql - Lazarus + Postgres: incomplete startup packet -

javascript - Ajax jqXHR.status==0 fix error -