我有一个用例,我的对象不得以任何方式复制.我在下面写了一个夸张的复制构造函数和复制赋值运算符删除的完整列表.有这么多,我无法确定使用哪些,有时这让我变得偏执.我不必在我的代码中全部写出来,是吗?因此,为了防止任何类型的对象复制,我应该使用哪些对象?
MyClass ( MyClass &) = delete;
MyClass (const MyClass &) = delete;
MyClass ( MyClass &&) = delete;
MyClass (const MyClass &&) = delete;
MyClass operator=( MyClass &) = delete;
MyClass operator=(const MyClass &) = delete;
const MyClass operator=( MyClass &) = delete;
const MyClass operator=(const MyClass &) = delete;
MyClass & operator=( MyClass &) = delete;
MyClass & operator=(const MyClass &) = delete;
const MyClass & operator=( MyClass &) = delete;
const MyClass & operator=(const MyClass &) = …
Run Code Online (Sandbox Code Playgroud) c++ copy-constructor copy-assignment deleted-functions implicit-methods
正如我在阅读这篇关于JDK 7中新的invokedynamic字节码指令的帖子所理解的那样,它可以调用对象类中没有静态定义的对象上的方法,并将这些方法调用解析为某些具体的静态方法.其他类通过拦截方法调用目标分辨率(帖子给出一个例子).
这是否意味着Java 7类可以使用Scala之类的隐式方法?如果不是,Scala中的隐式方法解析与invokedynamic方法解析有何不同?
我想为双精度数组定义一些隐式方法,以使我的代码更清晰.理想情况下,它们看起来像这样:
type Vec = Array[Double]
implicit def enrichVec(v: Vec) = new {
def /(x: Double) = v map (_/x)
def *(u: Vec) = (v zip u) map {case (x,y) => x*y} sum
def normalize = v / math.sqrt(v * v)
}
Run Code Online (Sandbox Code Playgroud)
但是,该normalize
函数无法正常工作,因为Scala不会递归地应用隐式方法.具体来说,我收到了一个错误Note: implicit method enrichVec is not applicable here because it comes after the application point and it lacks an explicit result type
.我可以通过明确写出代码来避免这种情况normalize
,但那会很难看.有更好的解决方案吗?
当类中有一个未定义移动操作的成员时,我很难理解隐式移动操作:
int main() {
struct A // no move: move = copy
{
A() = default;
A(const A&) {
cout << "A'copy-ctor\n";
};
A& operator=(const A&) {
cout << "A'copy-assign\n";
return *this;
}
};
struct B
{
B() = default;
A a; // does this make B non-moveable?
unique_ptr<int> upi;
// B(B&&) noexcept = default;
// B& operator=(B&&)noexcept = default;
};
A a;
A a2 = std::move(a); // ok use copy ctor instead of move one
a2 = std::move(a); // …
Run Code Online (Sandbox Code Playgroud) c++ copy-constructor move-constructor implicit-methods c++11