无法毫无问题地继承 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) {}
// 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;
}
实际上我也有一个处理数组的 auto_ptr 类的副本,但同样的错误也适用于 stl )
使用 GCC 4.3.0 的编译错误是:
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*)
我不明白为什么它与 autostr 参数作为 autostr(autostr&) 的有效参数不匹配。
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&).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
从函数返回的
autostr
是临时的。临时值只能绑定到 const 引用 (const autostr&
),但您的引用是非常量的。 (并且“正确地如此”。)这是一个可怕的想法,几乎没有一个标准库是打算继承的。我已经在您的代码中发现了一个错误:
std::string
有什么问题?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:
What's wrong with
std::string
?