相关疑难解决方法(0)

return-by vlaue 中的 C++ 复制构造函数激活

我无法找到以下问题的具体答案:

考虑以下代码:

Obj f() {
    Obj o2;
    return o2;
}

int main() {
    Obj o1 = f();
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

在没有编译器优化的情况下,复制构造函数被激活了多少次?

如果没有移动构造函数,不是一次将o2复制到调用函数,另一次构造o1吗?

如果有move构造函数,不是一次将 o2 复制到调用函数,另一次构造 o1 (第二次是 move const)?

c++ copy-constructor return-by-value

2
推荐指数
1
解决办法
261
查看次数

为什么命名返回值优化在这里不起作用?

我知道我已经删除了复制构造函数,我假设这没问题,因为我期望命名返回值优化并且会发生直接初始化。复制构造函数需要声明吗?如果我遇到了类成员也无法复制的问题,那么我该怎么办?

class UniqueBufferPointer
{public:
    UniqueBufferPointer() {}
    UniqueBufferPointer(const UniqueBufferPointer& other) = delete;
    UniqueBufferPointer(UniqueBufferPointer&& other) {}
    UniqueBufferPointer& operator=(const UniqueBufferPointer&) = delete;

};


struct GFXAPIImage
{
    GFXAPIImage() {}

    UniqueBufferPointer handle;
    GFXAPIImage(const GFXAPIImage&) = delete;
    //GFXAPIImage(const GFXAPIImage& other) = default; // If I use this instead of the compiler complaining that it can't access the copy constructor of this class, it complains it can't access the copy constructor of UniqueBufferPointer.

};


GFXAPIImage func()
{
    GFXAPIImage f;
    return f; //GFXAPIImage(const GFXAPIImage&) cannot be referenced, it …
Run Code Online (Sandbox Code Playgroud)

c++ return-value-optimization

2
推荐指数
1
解决办法
159
查看次数