-1

I have a shared pointer structure setup as such:

Class.h

std::shared_ptr<exampleClass> mSharedPtr;

Class.cpp

// Why do either of these calls work before reset() has been called on the shared pointer?
// Populates data from xml file
mSharedPtr->initialize();
bool returnValue = mSharedPtr->getBool();

Sidenote: When inspecting this variable in the VisualStudio debugger, the shared_ptr is null, as in pointing to nothing. I'm really confused as to why this isn't causing a crash.

Scrungo
  • 25
  • 1
  • 1
  • 6
  • They don't work. it is undefined behavior. smart pointers don't magically get around the rule that you need to initialize the pointer to a valid object if you want to use it. – NathanOliver Feb 05 '18 at 18:48
  • 3
    Undefined behavour is undefined. It can produce any result, including working as if nothing happened. – HolyBlackCat Feb 05 '18 at 18:48
  • If your `initialize()` doesn't touch any data member or call any virtual function, on common implementations, generally this code will not crash. – Matteo Italia Feb 05 '18 at 18:49
  • 3
    if you drive car blindfolded, you wont crash for sure, but you shouldnt count on it. – 463035818_is_not_an_ai Feb 05 '18 at 18:49
  • But smart_ptr is not POD. I'm trying to determine if an uninitialized smart_ptr is in fact an incompletely constructed object or not. If I write "smart_ptr foo;", can I expect that tests like "if (foo)" are valid? Or must it be initialized "smart_ptr foo(nullptr);"? Visual studio in debug mode is populating the uninitialized smart_ptr with 0xcdcdcdcd, causing tests like "if (foo) {// use foo}" to crash, and I'm wondering if this is correct behavior on VS's part, and bad coding on my part. For example, uninitialized STL objects are well-formed and empty, why not smart_ptr? – Bogatyr Oct 26 '18 at 15:30

1 Answers1

0

Because member functions for a class are like a global function that take this as a parameter. You can always set a pointer to null when calling a function. But if you try to do something with it, like accessing the pointed memory it will crash.

If you have virtual functions it will crash at the begging because it will try to access the vtable pointer.

This is what I noticed happening on Visual C++. Other compilers might do really odd stuff on undefined behavior.

Victor Padureanu
  • 604
  • 1
  • 7
  • 12