Pass shared_ptr trough functions

It is possible to use a standard (C++11) smart pointer to allocate memory for an object into a function (in ordinay function or in a dynamic library function),pass this pointer (the raw pointer) to caller and to make sure that the memory is released by the caller (could also be a program in 'pure' C)?
Why not?
How?
You can return the shared_ptr from the function (works for unique_ptr too).
Last edited on
If I return shared_ptr from my function, can declare the prototype as if it return the 'raw' pointer?
I would use my functions (and its prototype) also in C programs...
No. If you return a raw pointer the caller has to make sure to free the object.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <memory>

using namespace std;

std::shared_ptr<int> f(int x)
{
    std::shared_ptr<int> retValue(new (int));

    *retValue = x + 2;

    return retValue;
}


//my C program
int main()
{
        int result = f(4);//here can't use shared_ptr because this is a C program/function! :(
        return 0;
}


The problem is that would use (if it is possible) a smart pointer for allocate memory in a C++ function and to use this function in a C program. The C program should automatically deallocate the memory allocated in the C++ function (otherwise I get a memory leak)...
Using a C++ function in C is not going to work. Either make the function compatible with C, without smart pointers, and the caller will be responsible for the deallocation. If you are using this approach you probably want to provide a function to free the object because the caller doesn't know how it was allocated and therefore don't know how to deallocate it. Or you make a C++ function, with smart pointers, and only use them it from C++ code.
If you are using this approach you probably want to provide a function to free the object because the caller doesn't know how it was allocated and therefore don't know how to deallocate it.


Yes, this is my case.

There is a solution?
No, not the way you want it.
Topic archived. No new replies allowed.