编译器错误 C2448 返回 std 流
我有一个 Visual Studio 2008 C++ 程序,其中有我自己的流实现。像这样的东西:
class Foo : public std::ostream
{
public:
Foo( int a ) : std::ostream( &buf_ ) { };
Foo( boost::shared_ptr< int > a ) : std::ostream( &buf_ ) { };
private:
std::filebuf buf_;
};
class Bar
{
public:
Foo GetFoo() { return Foo( 1 ); };
Foo GetFoo2() { return Foo( boost::shared_ptr< int >( new int( 1 ) ) ); };
};
预期的用法是这样的:
Bar b;
Foo f = b.GetFoo(); // works fine
Foo f2 = b.GetFoo2(); // compiler error
不幸的是,这给了我一个关于 basic_ios 复制构造函数的编译器错误。
error C2248: 'std::basic_ios<_Elem,_Traits>::basic_ios' : cannot access private member declared in class 'std::basic_ios<_Elem,_Traits>'
为什么第一个 Foo( int )
构造函数可以被编译器接受,但涉及 boost::shared_ptr
的构造函数却不能?
谢谢, 保罗·H
I have a Visual Studio 2008 C++ program where I have my own stream implementation. Something like this:
class Foo : public std::ostream
{
public:
Foo( int a ) : std::ostream( &buf_ ) { };
Foo( boost::shared_ptr< int > a ) : std::ostream( &buf_ ) { };
private:
std::filebuf buf_;
};
class Bar
{
public:
Foo GetFoo() { return Foo( 1 ); };
Foo GetFoo2() { return Foo( boost::shared_ptr< int >( new int( 1 ) ) ); };
};
The intended usage is like this:
Bar b;
Foo f = b.GetFoo(); // works fine
Foo f2 = b.GetFoo2(); // compiler error
Unfortunately, this gives me a compiler error about the basic_ios copy constructor.
error C2248: 'std::basic_ios<_Elem,_Traits>::basic_ios' : cannot access private member declared in class 'std::basic_ios<_Elem,_Traits>'
Why is the first Foo( int )
constructor okay with the compiler, but the one involving a boost::shared_ptr
is not?
Thanks,
PaulH
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的 Foo 类继承自不可复制的类,但您没有实现复制构造函数。当您像在 getter 函数中那样按值传递 Foo 的实例时,必然会遇到麻烦。
GetFoo
起作用的原因可能是返回值优化消除了复制构造,但这并不意味着您可以这样做。Your
Foo
class is inheriting from a non-copyable class, yet you are not implementing the copy constructor. You are bound to get into trouble when you pass instances ofFoo
by value, as you do in the getter functions.The reason that
GetFoo
works might be that return-value optimization is eliding the copy construction, but this doesn't mean that you're allowed to do this.