Can't inherit from auto_ptr without problems

血红的双手。 提交于 2019-12-12 01:31:38

问题


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?



来源:https://stackoverflow.com/questions/2910157/cant-inherit-from-auto-ptr-without-problems

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!