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:错误:没有匹配的函数调用“autostr::autostr(autostr)”
main.cpp:147:注意:候选人是:autostr::autostr(autostr&)
main.cpp:146:注意:autostr::autostr(char*)

我不明白为什么它不匹配 autostr 参数作为 autostr(autostr&) 的有效参数。

4

1 回答 1

1

从函数返回的autostr是临时的。临时值只能绑定到引用到 const ( const autostr&),但您的引用是非常量的。(而且“理所当然”。)

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

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

有什么问题std::string

于 2010-05-26T05:08:05.630 回答