Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save kjelloh/c5fed41cbbe0a34ef843108d134d6c11 to your computer and use it in GitHub Desktop.
Save kjelloh/c5fed41cbbe0a34ef843108d134d6c11 to your computer and use it in GitHub Desktop.
Elaboration on Herb Sutter Core Guidlines example for Smart Pointers (See 57:45 into https://youtu.be/hEx5DNLWGgA)
//
// main.cpp
// MySharedPtrPlayGround
//
// Created by Kjell-Olov Högdahl on 2016-08-15.
// Copyright © 2016 Kjell-Olov Högdahl. All rights reserved.
//
#include <iostream>
#include <memory> // shared_ptr
// Elaboration on Herb Sutter Core Guidlines example for Smart Pointers (See 57:45 into https://youtu.be/hEx5DNLWGgA)
auto gsp = std::make_shared<int>();
void f(int* p) {
// Mutate globally accessible owner
gsp.reset(); // (1) If called with f(gsp.get()) gsp.reset() will invalidate existence of *p
// (2) If called with f(sp.get()) gsp.reset() will NOT invalidate existence of *p.
*p = 4; // Ok as long as *p is not owned by global gsp.
}
void g(std::shared_ptr<int>& sp,int* p) {
// Mutate passed non-const owner
sp.reset(); // (3) if called with g(sp_x,sp_x.get()) (sp_x some shared pointer) sp.reset() will invalidate existence of *p.
// (4) If called with (sp_x, sp_y.get()) (sp_x and sp_y shared pointers owning different objects) sp.reset will NOT invalidate existence of *p.
*p = 4; // Ok as long as *p is not owned by passed sp
}
int main(int argc, const char * argv[]) {
// See "R.37: Do not pass a pointer or reference obtained from an aliased smart pointer" at (https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines.html#a-namerr-smartptrgetar37-do-not-pass-a-pointer-or-reference-obtained-from-an-aliased-smart-pointer)
f(gsp.get()); // (1) Error: f may invalidate existence of accessible *p (*gsp.get()) e.g., by calling gsp.reset()
// Hint: gsp is in global scope and thus accessible by f.
// ==> So don't pass raw pointer or reference to global scope owned object
auto sp = gsp; // Pin existence of gsp owned object to this stack
f(sp.get()); // (2) OK. sp keeps int owned by gsp alive while call to f.
g(gsp,gsp.get()); // (3) Error: g may invalidate existence of accessible *p (*gsp.get()) e.g., by sp.reset().
// Hint: g gets gsp access by non-const reference parameter sp.
// ==> So don't pass mutable owner to g of objects used by g.
g(gsp, sp.get()); // (4) Ok. Inside g *p will exist during whole call whatever g does with passed or global owners
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment