Zack
Zack

Reputation: 1245

Pass const shared_ptr as argument

I have an issue understanding this code which is in a .m Objective-C file.

void Execute (const std::shared_ptr<RProgram> program) {}

What's the advantage of passing by const? I don't know if it has perf advantage or it shares the ownership of program?

I understand the following patterns

// this just takes the reference without changing the counter for perf. 
void Execute (const std::shared_ptr<RProgram>& program) {} 
// this takes ownership 
void Execute (std::shared_ptr<RProgram> program) {} 

Upvotes: 0

Views: 77

Answers (1)

463035818_is_not_an_ai
463035818_is_not_an_ai

Reputation: 122830

The const in this signature

void Execute (const std::shared_ptr<RProgram> program) {}

means that inside the function program is const. Calling any non-const method would result in a compiler error. However, it has little to no meaning for the caller. It is not even considerd for the type of the function:

#include <memory>
#include <iostream>
#include <type_traits>

void foo(const int) {}
void bar(int)  {}

void f(const std::shared_ptr<int>) {}
void g(std::shared_ptr<int>) {}

int main() {
    std::cout << std::is_same_v< decltype(foo),decltype(bar)> << "\n";
    std::cout << std::is_same_v< decltype(f),decltype(g)> << "\n";
}

Output:

1
1

Upvotes: 2

Related Questions