Re: returning a std::auto_ptr, a question of style
On Aug 30, 12:37 am, Andrew <marlow.and...@googlemail.com> wrote:
I was looking for general advice on how to declare a function that
employs the virtual ctor pattern where the caller is given the
responsibility to delete the memory. I admit that if such a function
was declared to return an auto_ptr it would make life difficult for
the user code that wanted to share the ownership. But a library that
declares a virtual ctor function in such a way does not want user code
to share the ownership. Is that such a bad thing? Surely it is better
to have a clear division of responsibilities. Surely it is better to
employ coding conventions that make it hard to a user of the library
to get it wrong. Declaring the function to return a naked pointer is
certainly error-prone, whilst at the same time being very flexible.
The user can assign the result to a smart pointer of his own choosing.
Or he can forget to, in which case there will be a memory leak.
#include <memory>
#include <iostream>
std::auto_ptr<int> source() {return std::auto_ptr<int>(new int(3));}
std::shared_ptr<int> shared_source() {return std::shared_ptr<int>(new
int(3));}
int main()
{
// Ok to share
std::shared_ptr<int> p_shared = source();
std::cout << *p_shared << '\n';
// Ok not to share
std::auto_ptr<int> p_unique = source();
std::cout << *p_unique << '\n';
// Ok to share
std::shared_ptr<int> p_shared2 = shared_source();
std::cout << *p_shared2 << '\n';
// Must share
std::auto_ptr<int> p_unique2 = shared_source();
std::cout << *p_unique2 << '\n';
}
Everything works except the line below "Mush share":
error: conversion from ?std::shared_ptr<int>? to non-scalar type
?std::auto_ptr<int>? requested
std::auto_ptr<int> p_unique2 = shared_source();
-Howard
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]