Can't inherit from auto_ptr without problems

2019-09-06 19:12发布

问题:

What I want to do is this:

#include <memory>

class autostr : public std::auto_ptr<char>
{
public:
    autostr(char *a) : std::auto_ptr<char>(a) {}
    autostr(autostr &a) : std::auto_ptr<char>(a) {}
    // define a bunch of string utils here...
};

autostr test(char a)
{
    return autostr(new char(a));
}

void main(int args, char **arg)
{
    autostr asd = test('b');
    return 0;
}

(I actually have a copy of the auto_ptr class that handles arrays as well, but the same error applies to the stl one)

The compile error using GCC 4.3.0 is:

main.cpp:152: error: no matching function for call to `autostr::autostr(autostr)'
main.cpp:147: note: candidates are: autostr::autostr(autostr&)
main.cpp:146: note:                 autostr::autostr(char*)

I don't understand why it's not matching the autostr argument as a valid parameter to autostr(autostr&).

回答1:

The autostr that is returned from the function is a temporary. Temporary values can only be bound to references-to-const (const autostr&), but your reference is non-const. (And "rightly so".)

This is a terrible idea, almost none of the standard library is intended to be inherited from. I already see a bug in your code:

autostr s("please don't delete me...oops");

What's wrong with std::string?



标签: c++ gcc auto-ptr