gpt4 book ai didi

c++ - 不能毫无问题地从 auto_ptr 继承

转载 作者:行者123 更新时间:2023-11-28 08:29:12 25 4
gpt4 key购买 nike

我想做的是:

#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&) 的有效参数。

最佳答案

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

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

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

std::string 有什么问题?

关于c++ - 不能毫无问题地从 auto_ptr 继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2910157/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com