gpt4 book ai didi

C++ - 在创建时调用赋值运算符而不是复制构造函数

转载 作者:太空宇宙 更新时间:2023-11-04 14:58:14 25 4
gpt4 key购买 nike

我想在类似于 native 类型的结构之间强制执行显式转换:

int i1;
i1 = some_float; // this generates a warning
i1 = int(some_float): // this is OK
int i3 = some_float; // this generates a warning

我想使用赋值运算符和复制构造函数来做同样的事情,但行为不同:

Struct s1;
s1 = other_struct; // this calls the assignment operator which generates my warning
s1 = Struct(other_struct) // this calls the copy constructor to generate a new Struct and then passes that new instance to s1's assignment operator
Struct s3 = other_struct; // this calls the COPY CONSTRUCTOR and succeeds with no warning

是否有任何技巧可以实现第三种情况 Struct s3 = other_struct; 使用默认构造函数构造 s3 然后调用赋值运算符?

这一切都按预期编译和运行。 C++ 的默认行为是在创建新实例时调用复制构造函数而不是赋值运算符立即调用复制构造函数,(即 MyStruct s = other_struct; 变成 MyStruct s(other_struct);而不是 MyStruct s; s = other_struct;。我只是想知道是否有任何技巧可以解决这个问题。

编辑:“显式”关键字正是我所需要的!

class foo {
foo(const foo& f) { ... }
explicit foo(const bar& b) { ... }
foo& operator =(const foo& f) { ... }
};

foo f;
bar b;
foo f2 = f; // this works
foo f3 = b; // this doesn't, thanks to the explicit keyword!
foo f4 = foo(b); // this works - you're forced to do an "explicit conversion"

最佳答案

免责声明:我准备对此投反对票,因为这没有回答问题。但这可能对 OP 有用。

我认为将复制构造函数视为默认构造+赋值是一个非常糟糕的主意。恰恰相反:

struct some_struct
{
some_struct(); // If you want a default constructor, fine
some_struct(some_struct const&); // Implement it in the most natural way
some_struct(foo const&); // Implement it in the most natural way

void swap(some_struct&) throw(); // Implement it in the most efficient way

// Google "copy and swap idiom" for this one
some_struct& operator=(some_struct x) { x.swap(*this); return *this; }

// Same idea
some_struct& operator=(foo const& x)
{
some_struct tmp(x);
tmp.swap(*this);
return *this;
}
};

以这种方式实现事物是万无一失的,并且是您在 C++ 中的转换语义方面可以获得的最佳方式,因此这是此处的方式。

关于C++ - 在创建时调用赋值运算符而不是复制构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3737286/

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