不能继承auto_ptr没有问题 [英] Can't inherit from auto_ptr without problems

查看:166
本文介绍了不能继承auto_ptr没有问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做的是:

  #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){}
//定义一组字符串utils here ...
};

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

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

(我实际上有一个auto_ptr类的副本处理数组,但同样的错误适用于stl一个)



使用GCC 4.3.0的编译错误是:

 main.cpp:152:错误:没有匹配的函数调用`autostr :: autostr(autostr)'
main.cpp:147:注意:候选人是:autostr :: autostr $ b main.cpp:146:注意:autostr :: autostr(char *)



我不明白为什么它不匹配autostr参数 c> 从函数返回的是一个临时的。临时值只能绑定到references-to-const( const autostr& ),但是你的引用是非const。 (和正确的。)



这是一个可怕的想法,几乎没有一个标准库打算继承。我已经在您的代码中看到一个错误:

  autostrs(请不要删除我... oops 

std :: string 有什么问题?


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&).

解决方案

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?

这篇关于不能继承auto_ptr没有问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆