Writing Good C++14... By Default

Play Writing Good C++14... By Default

The Discussion

  • User profile image

    I can't understand the example about shared_ptr (slide precisely at 1:00:00).
    Here's what Herb claims there:

    void f(int* p) { /* might invalidate p */ };
    shared_ptr<int> global_sp = make_shared<int>();
    int main() {
    f(global_sp.get()); // bad, and tool confirms it
    auto local_sp = global_sp;
    f(local_sp.get()); // OK, checker tool also has no complaints.
    return 0;

    I don't see why second case is a "good weather" scenario.
    When the statement "local_sp = global_sp" is executed, there's still a single copy of data, which they both point to.
    Given that, if f does something like "void f(int* p) { delete p; }", then f(local_sp.get()) will invalidate both local_sp and global_sp, so the issue actually becomes even worse.

    Am I wrong anywhere in my deduction?

  • User profile image
    John Lysons

    Could it be that there is already a rule that we don't do raw deletes but can reset shared pointers.
    So the problem is if f does gsp.reset() or g dies parameter 1.reset().

Add Your 2 Cents