在阅读Scott Meyers所着的"更有效的C++"一书的第20和22项后,我决定提出这个问题.
假设你写了一个代表有理数的类:
class Rational
{
public:
Rational(int numerator = 0, int denominator = 1);
int numerator() const;
int denominator() const;
Rational& operator+=(const Rational& rhs); // Does not create any temporary objects
...
};
Run Code Online (Sandbox Code Playgroud)
现在让我们说你决定operator+使用operator+=:
const Rational operator+(const Rational& lhs, const Rational& rhs)
{
return Rational(lhs) += rhs;
}
Run Code Online (Sandbox Code Playgroud)
我的问题是:如果禁用返回值优化,将创建多少个临时变量operator+?
Rational result, a, b;
...
result = a + b;
Run Code Online (Sandbox Code Playgroud)
我相信会创建2个临时值:一个Rational(lhs)是在body体内执行的operator+,另一个operator+是在返回的值是通过复制第一个临时值创建的.
当Scott提出这个操作时,我的困惑出现了:
Rational result, a, b, …Run Code Online (Sandbox Code Playgroud) c++ effective-c++ operator-keyword return-value-optimization copy-elision
几天来我一直在尝试解决这个视觉错误,但没有成功,所以我问这个问题是为了看看是否有人可以帮助我理解发生了什么。
首先,我将在没有任何代码的情况下描述问题,然后我将提供一些代码。情况如下:
我的 OpenGL 应用程序将此图像渲染到多重采样帧缓冲区:
然后,我将该多重采样帧缓冲区传输到常规帧缓冲区(不是多重采样帧缓冲区)。
然后,我使用 将该常规帧缓冲区中的 RGB 数据读取到无符号字节数组中glReadPixels。
最后,我stbi_write_png使用无符号字节数组进行调用。这是结果:
对我来说,第一行字节被向右移动,这导致所有其他行被移动,从而形成对角线形状。
这是我的代码:
int width = 450;
int height = 450;
int numOfSamples = 1;
// Create the multisample framebuffer
glGenFramebuffers(1, &mMultisampleFBO);
glBindFramebuffer(GL_FRAMEBUFFER, mMultisampleFBO);
// Create a multisample texture and use it as a color attachment
glGenTextures(1, &mMultisampleTexture);
glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, mMultisampleTexture);
glTexImage2DMultisample(GL_TEXTURE_2D_MULTISAMPLE, numOfSamples, GL_RGB, width, height, GL_TRUE);
glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, 0);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D_MULTISAMPLE, mMultisampleTexture, 0);
// Create a multisample renderbuffer object and use it as a depth …Run Code Online (Sandbox Code Playgroud) 这个问题是基于Scott Meyers在他的"更有效的C++"一书中提供的一个例子.考虑以下课程:
// A class to represent the profile of a user in a dating site for animal lovers.
class AnimalLoverProfile
{
public:
AnimalLoverProfile(const string& name,
const string& profilePictureFileName = "",
const string& pictureOfPetFileName = "");
~AnimalLoverProfile();
private:
string theName;
Image * profilePicture;
Image * pictureOfPet;
};
AnimalLoverProfile::AnimalLoverProfile(const string& name,
const string& profilePictureFileName,
const string& pictureOfPetFileName)
: theName(name)
{
if (profilePictureFileName != "")
{
profilePicture = new Image(profilePictureFileName);
}
if (pictureOfPetFileName != "")
{
pictureOfPet = new Image(pictureOfPetFileName); // Consider …Run Code Online (Sandbox Code Playgroud) c++ ×3
constructor ×1
copy-elision ×1
destructor ×1
exception ×1
fbo ×1
memory-leaks ×1
opengl ×1
png ×1
stb-image ×1