gpt4 book ai didi

c++ - 哪个更好 : a lying copy constructor or a non-standard one?

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:54:20 25 4
gpt4 key购买 nike

我有一个包含不可复制句柄的 C++ 类。但是,该类必须有一个复制构造函数。因此,我实现了一个将句柄的所有权转移到新对象的方法(如下所示),

class Foo
{
public:
Foo() : h_( INVALID_HANDLE_VALUE )
{
};

// transfer the handle to the new instance
Foo( const Foo& other ) : h_( other.Detach() )
{
};

~Foo()
{
if( INVALID_HANDLE_VALUE != h_ )
CloseHandle( h_ );
};

// other interesting functions...

private:

/// disallow assignment
const Foo& operator=( const Foo& );

HANDLE Detach() const
{
HANDLE h = h_;
h_ = INVALID_HANDLE_VALUE;
return h;
};

/// a non-copyable handle
mutable HANDLE h_;
}; // class Foo

我的问题是标准复制构造函数采用常量引用,而我正在修改该引用。所以,我想知道哪个更好(以及为什么):

  1. 一个非标准的复制构造函数: Foo( Foo& other );

  2. “谎言”的复制构造函数: Foo( const Foo& other );


编辑:

DuplicateHandle()仅适用于特定类型的句柄。这不是其中的一个。不能复制、复制或克隆此句柄。

有几个人指出我错误地暗示它是一个非标准的复制构造函数并且 std::auto_ptr做这个。我认为这可能是要走的路。但是,当我使复制构造函数采用非常量值时,每次使用该类时,我都会收到警告。例如:

namespace detail {
class Foo { ... };
};

class Buzz
{
public:
typedef detail::Foo Fuzz;

Fuzz bar() const { return Fuzz(); }; // warning here
};

warning C4239: nonstandard extension used : 'argument' : conversion from 'Foo' to 'Foo &'
1> A non-const reference may only be bound to an lvalue; copy constructor takes a reference to non-const

有人可以建议我应该如何处理它们吗?


编辑2:

似乎每个人都在引导我走向 std::auto_ptr<>做事的方法。所以,我在那里看了看,它使用中间结构来解决我在第一次编辑中描述的问题。这是我想出的解决方案。

class Foo;

struct Foo_ref
{
explicit Foo_ref( Foo& other ) : ref_( other ) {};
Foo& ref_;
private:
const Foo_ref& operator=( const Foo_ref& );
}; // struct Foo_ref

class Foo
{
public:
Foo() : h_( INVALID_HANDLE_VALUE )
{
};

// transfer the handle to the new instance
Foo( Foo_ref other ) : h_( other.ref_.Detach() )
{
};

~Foo()
{
if( INVALID_HANDLE_VALUE != h_ )
CloseHandle( h_ );
};

operator Foo_ref()
{
Foo_ref tmp( *this );
return tmp;
};

// other interesting functions...

private:

/// disallow assignment
const Foo& operator=( const Foo& );

HANDLE Detach()
{
HANDLE h = h_;
h_ = INVALID_HANDLE_VALUE;
return h;
};

/// a non-copyable handle
HANDLE h_;
}; // class Foo

它在警告级别 4 上可以干净地编译并且似乎可以工作。请让我知道它是否比我原来的帖子更不负责任。

最佳答案

两者都很糟糕。如果你的类有一个不可复制的成员变量,那么你的类就是不可复制的。

如果让你的类不可复制真的是 Not Acceptable ,一个解决方法是有一个共享指针指向一个“状态”类/结构来存储不可复制的对象(它本身是不可复制的),但是你的类可以复制共享指针通过标准复制构造函数。

关于c++ - 哪个更好 : a lying copy constructor or a non-standard one?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3007393/

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