gpt4 book ai didi

c++ - 复制省略的条件?

转载 作者:可可西里 更新时间:2023-11-01 15:41:39 26 4
gpt4 key购买 nike

我想验证以下优化是否按预期工作:

  • RVO
  • 命名 RVO
  • 按值传递参数时复制省略

所以我写了这个小程序:

#include <algorithm>
#include <cstddef>
#include <iostream>
#include <vector>

struct Foo {
Foo(std::size_t length, char value) : data(length, value) { }

Foo(const Foo & rhs) : data(rhs.data) { std::cout << "*** COPY ***" << std::endl; }

Foo & operator= (Foo rhs) {
std::cout << "*** ASSIGNMENT ***" << std::endl;
std::swap(data, rhs.data); // probably expensive, ignore this please
return *this;
}

~Foo() { }

std::vector<char> data;
};

Foo TestRVO() { return Foo(512, 'r'); }

Foo TestNamedRVO() { Foo result(512, 'n'); return result; }

void PassByValue(Foo inFoo) {}

int main()
{
std::cout << "\nTest RVO: " << std::endl;
Foo rvo = TestRVO();

std::cout << "\nTest named RVO: " << std::endl;
Foo named_rvo = TestNamedRVO();

std::cout << "\nTest PassByValue: " << std::endl;
Foo foo(512, 'a');
PassByValue(foo);

std::cout << "\nTest assignment: " << std::endl;
Foo f(512, 'f');
Foo g(512, 'g');
f = g;
}

我在启用优化的情况下编译了它:

$ g++ -o test -O3 main.cpp ; ./test

这是输出:

Test RVO: 

Test named RVO:

Test PassByValue:
*** COPY ***

Test assignment:
*** COPY ***
*** ASSIGNMENT ***

根据输出 RVO 和命名 RVO 按预期工作。但是,赋值运算符和调用 PassByValue 时不会执行复制省略。

用户定义的复制构造函数是否不允许复制省略? (我知道标准明确允许 RVO,但我不知道按值传递时的复制省略。)有没有一种方法可以在不定义复制构造函数的情况下验证复制省略?

最佳答案

标准说(在第 12.8.15 段中):

This elision of copy operations is permitted in the following circumstances (which may be combined to eliminate multiple copies):

  • in a return statement in a function with a class return type, when the expression is the name of a non-volatile automatic object with the same cv-unqualified type as the function return type, the copy operation can be omitted by constructing the automatic object directly into the function’s return value

  • when a temporary class object that has not been bound to a reference (12.2) would be copied to a class object with the same cv-unqualified type, the copy operation can be omitted by constructing the tempo- rary object directly into the target of the omitted copy

这两种情况都不适用于此处,因此不允许省略。第一个很明显(不返回)。第二种是不允许的,因为你传入的对象不是临时的。

请注意,您的代码仍然没有问题,因为无论如何您都必须创建拷贝。要删除该拷贝,您将不得不使用 C++0x 的移动语义。

关于c++ - 复制省略的条件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6383639/

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