C ++在什么条件下优化构造函数调用? [英] Under what conditions does C++ optimize out constructor calls?

查看:131
本文介绍了C ++在什么条件下优化构造函数调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为一个矩阵运算写一个类,我正在实现的一个特性是,你可以切割一个矩阵并返回另一个矩阵,但返回的矩阵引用父节点的内存。这是非常有用的,如果你想要的东西,比如获取一个矩阵的子部分或添加一个向量到列或类似的东西。

I'm writing a class for Matrix arithmetic, and one feature I'm implementing is that you can "slice" a matrix and get another matrix back, but done such that the returned matrix references the parent's memory. This is very useful if you want to things like get a subsection of a matrix or add a vector to a column or things like that.

但是,我想实现它,使得如果分配或复制返回的矩阵,则别名被破坏并且内存被复制,所以你不能轻易

However, I wanted to implement it so that if the returned matrix is assigned or copied, the aliasing is broken and the memory is copied, so that you can't easily pass an aliased matrix around forever.

在使用这个时,我有这样的:

In playing with this, I have something like this:

matrix B = A.slice(1,1);  

A.slice(1,1)返回A的子矩阵(偏移1行1柱)。我实现了=运算符打破别名,但对我的麻烦,它不被调用时,这样做,即使与-O0开。类似地:

A.slice(1,1) returns a sub-matrix of A (offset 1 row and 1 column). I implemented the = operator to break the aliasing, but to my chagrine, it isn't called when doing this, even with -O0 on. Similarly:

matrix B(A.slice(1,1)); 

不调用复制构造函数(也写为中断别名)。唯一可行的是:

Doesn't call the copy constructor (also written to break aliasing). The only thing that works is:

matrix B; B = A.slice(1,1);

我的问题是,显然,因为我在前两个示例中直接从A初始化B,采用某种快捷方式,而我在上一个示例中显式创建B,然后 将A.slice(1,1)分配给它。

My question is, obviously since I'm initializing B directly from A in the first two examples, it's taking some sort of shortcut, while I explicitly create B first in the last example and then assign A.slice(1,1) to it.

有人可以告诉我一些关于在调用复制构造函数和赋值运算符时的规则如何?

Can someone provide me with some insight into what the rules are in cases like these for when copy constructors and assignment operators are called?

推荐答案

这称为复制elision 返回值优化(§12.8.31的C ++ 11标准)。复制构造函数可以跳过几乎任何返回类类型的函数。这通常与返回类类型的实际实现密切相关。 (注意,你也可以这样依赖这个:假设 slice 按值返回你的矩阵类型,你不想要一个拷贝构造函数您的别名。)

This is called copy elision, or return value optimization (§12.8.31 of the C++11 standard). The copy constructor can be skipped for virtually any function that returns a class type. This is often closely related to the actual implementation of returning class types. (Note that you're sort of relying on this too: presumably slice returns your matrix type by value, and you don't want a copy constructor called there if it would break your aliasing.)

您可能需要以其他方式实现此功能,例如 slice 返回某种类型的代理类型,它支持相同的操作,并可以转换为您的正常矩阵类型,在转换期间中断别名。

You'll most likely need to implement this in some other way—for example, slice returning some kind of proxy type that supports the same operations and can convert to your normal matrix type, breaking aliasing during that conversion.

这篇关于C ++在什么条件下优化构造函数调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆