无法毫无问题地继承 auto_ptr

发布于 2024-09-02 19:22:02 字数 798 浏览 9 评论 0原文

我想做的是这样的:(

#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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

挖个坑埋了你 2024-09-09 19:22:02

从函数返回的 autostr 是临时的。临时值只能绑定到 const 引用 (const autostr&),但您的引用是非常量的。 (并且“正确地如此”。)

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

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

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:

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

What's wrong with std::string?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文